Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window resize event fires twice in jQuery

Tags:

jquery

I ran the below code

$(document).ready(function() {

    var ivar = 0;

    $(window).resize(function() {
        console.log('$(window).height() ' + $(window).height() + ' - ' + ++ivar);
    });
});​

whenever i resize i found the event was firing twice i.e. the counter 'ivar' is incremented twice.

Can any one advise me whats happening in the resize event that makes the counter to get incremeted twice

**Edit: 1. I'm resizing the window by double-clicking on the window bar.


Thanks

like image 699
µMax Avatar asked Nov 06 '12 05:11

µMax


People also ask

What is use of $( window resize ();?

Definition and UsageThe onresize event occurs when the browser window has been resized. Tip: To get the size of an element, use the clientWidth, clientHeight, innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or offsetHeight properties.

What is Resize event in jQuery?

The 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 is Resize event in JavaScript?

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.


1 Answers

That's the very well known problem. In some browsers resize is called twice. We can create timer so it will call our function only when the user stops resizing the window. Here's how you can do it:

var globalTimer = null;

$(window).resize(function() {
    clearTimeout(globalTimer);
    globalTimer = setTimeout(doneResize, 500);
});

function doneResize(){
  console.log('$(window).height() ' + $(window).height() + ' - ' + ++ivar);   
}​
like image 107
Kirill Ivlev Avatar answered Nov 13 '22 06:11

Kirill Ivlev