Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onresize fires twice

Tags:

javascript

I'm new to js. Please, don't kick painfully. I have this code

    window.onresize=function() {alert(1);};

When I resize any browser`s window, this function fires twice. Why? And how to rewrite this code that code will fire once.

Thanx in advance.

like image 278
macloving Avatar asked Apr 04 '13 13:04

macloving


2 Answers

You need a timeout to bundle the resize events.

var res;
window.onresize=function() {
    if (res){clearTimeout(res)};
    res = setTimeout(function(){console.log("resize triggered");},100);
};

live Example

like image 193
Christoph Avatar answered Oct 27 '22 19:10

Christoph


This event will fire multiple times in different browsers (some once you've finished the the resize, others during).

One way to get around this is to wait a certain amount of time (say half a second) after the event fires, to see if there are further updates. If not, you can proceed with the alert.

e.g.

var resizeTimer;
window.onresize = function(){
    if (resizeTimer){
        clearTimeout(resizeTimer);
    } 
    resizeTimer = setTimeout(function(){
        alert(1);
        }, 500);
};

See it work on this fiddle.

like image 31
Graham Avatar answered Oct 27 '22 19:10

Graham