Window.onresize fires twice

I am new to js. Please do not be hurt. I have this code

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

When resizing the browser window, this function works twice. What for? And how to rewrite this code, the code of which will fire once.

Thanx in advance.

+5
source share
4 answers

You will need a timeout to combine the resize events.

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

live example

+10
source

This event will fire several times in different browsers (some after resizing, others during).

One way around this is to wait a while (say, half a second) after the fire occurs to find out if there are any additional updates. If not, you can continue the warning.

eg.

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

, .

+6

""

var doc = document; //To access the dom only once
var cWidth = doc.body.clientWidth;
var newWidth = cWidth; //If you want a log to show at startup, change to: newWidth = 0
window.onresize = function (){
    newWidth = doc.body.clientWidth;
    if(cWidth != newWidth){
        cWidth = newWidth;
        console.log("clientWidth:", cWidth); //instead of alert(cWidth);
     };
};
+1

I propose another solution because I don’t like timeouts,

   `var resized;
    window.onresize = function () {
        if(resized){
            resized = false;
        }
        else{
            resized = true;
            alert('resize');
        }
    };`
0
source

All Articles