Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to know if window is resizing in width/height or both?

I have a little problem with window resizing using jQuery's 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 width is for 50px bigger than div and if height is for 50px bigger than div,

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

then is working on just one condition and I can resize only width or height.

How could I know which dimension is changing in size or if both are?

like image 933
user1257255 Avatar asked Sep 30 '12 12:09

user1257255


People also ask

How does jQuery determine window resize?

jQuery resize() MethodThe resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.

What happen when window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

How do I capture a Windows resize event?

Answer: Use the addEventListener() Method You can simply use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window. addEventListener('resize', ...) . The following example will display the current width and height of the browser window on resize.


2 Answers

By saving last window size values 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;
});
like image 154
Anoop Avatar answered Nov 16 '22 03:11

Anoop


Save the previous size and compare with it, everytime the size changes.

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/

like image 44
techfoobar Avatar answered Nov 16 '22 03:11

techfoobar