macloving
macloving

Reputation: 1277

window.onresize fires twice

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.

Upvotes: 5

Views: 8189

Answers (4)

McCoy Web Developer
McCoy Web Developer

Reputation: 25

To prevent function from "firing" the same result more than once when user resize

var doc = document; //Access the dom only once
var currentWidth = doc.body.clientWidth;
var newWidth = currentWidth; //If you want to "fire" at startup, change to: var newWidth = 0
window.onresize = function (){
    newWidth = doc.body.clientWidth;
    if(currentWidth != newWidth){
        currentWidth = newWidth;

        //Fire the results     
        console.log("clientWidth:", currentWidth);
     };
};

Upvotes: 2

josean
josean

Reputation: 1

I propose other solution because I don't like the timeouts,

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

Upvotes: 0

Christoph
Christoph

Reputation: 51201

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

Upvotes: 9

Graham
Graham

Reputation: 6562

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.

Upvotes: 6

Related Questions