Window resize event fires twice in jQuery

I ran the code below

$(document).ready(function() { var ivar = 0; $(window).resize(function() { console.log('$(window).height() ' + $(window).height() + ' - ' + ++ivar); }); });โ€‹ 

whenever I resize, I find that the event fired twice, i.e. the ivar counter doubles.

Can someone tell me what happens in a resize event that causes the counter to double increase

** Edit: 1. I resize the window by double-clicking on the window pane.


thanks

+6
source share
2 answers

This is a very famous issue. In some browsers, the size is changed twice. We can create a timer to 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); }โ€‹ 
+9
source

The resize event is fired every time the window is resized. There is no guarantee how often the event will fire. The browser may decide to resize as soon as the mouse cursor drags the corner and continues to do so until the mouse is released so that it can constantly redraw the contents. The last event is the one that is taken into account when you release the mouse button.

This can happen if the browser window is maximized by double-clicking. The OS may decide to animate the contents of the window by firing several resize events in the browser. A browser that wants to redraw accurately can propagate events further, thereby causing a double size, even if the animation is very fast.

As Kir Ivlev suggests, you can wait a little after each resize to see if another resize will occur. If so, extend the wait (stop waiting and wait again)

+6
source

All Articles