JQuery - How do I know if a window is resized in width / height or both?

I have a small problem with resizing a window using jQuery function . resize () . I would like to know which dimension is getting bigger / smaller - width or height. I need this because if I just put two conditions - if the width for 50px is bigger than the div, and if the height for 50px is bigger than the div,

// (pseudocode) if width = div.width + 50px width = something if height = div.height + 50px height = something 

then it only works with one condition, and I can only resize width or height.

How can I find out which dimension is resizing, or both?

+8
javascript jquery resize window
source share
2 answers

By storing the size of the last window in variables.

 var h = $(window).height(), w = $(window).width(); $(window).resize(function(){ var nh = $(window).height(), nw = $(window).width(); // compare the corresponding variables. h = nh; w = nw; // update h and w; }); 
+19
source share

Keep the previous size and compare it with each resize.

For ex:

 var prevW = -1, prevH = -1; $(document).ready(function() { // ... other stuff you might have inside .ready() prevW = $(window).width(); prevH = $(window).height(); }); $(window).resize(function() { var widthChanged = false, heightChanged = false; if($(window).width() != prevW) { widthChanged = true; } if($(window).height() != prevH) { heightChanged = true; } // your stuff prevW = $(window).width(); prevH = $(window).height(); }); 

Demo: http://jsfiddle.net/44aNW/

+3
source share

All Articles