javascript - dynamic margin based on jQuery window.width() -


i have little problem jquery function. need add margin element when window.width < 580px , need remove when window.width larger. here problem, first part of function work well, not second.

var wwidth= $(window).width();  if ( wwidth < 582) {     $( window ).resize(function() {       var nwwidth=$( document ).width();     var marginl = (nwwidth - 292)/2;      $('.hub-item').css('margin-left',marginl +'px');     }); } else {      $( window ).resize(function() {       $('.hub-item').css('margin-left','0px');     });  } 

i have no mystakes in console margin not 0. u all!

edit : correct code :

$(window).resize(function() {     var wwidth= $(this).width();     if (wwidth < 582) {         var nwwidth=$( window ).width();         var marginl = (nwwidth - 292)/2;          $('.hub-item').css('margin-left',marginl +'px');     }     else {         $('.hub-item').css('margin-left','0px');     } }); 

thanks all!

you need put if statement within $(window).resize() function, , recalculate wwidth every time:

$(window).resize(function() {     var wwidth = $(this).width();      if (wwidth < 582) {         ...     }     else {         ...     } }); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -