window.resize event firing in Internet Explorer window.resize event firing in Internet Explorer jquery jquery

window.resize event firing in Internet Explorer


I just discovered another problem which might help you.

I am using jQuery and I have window.resize event to call a function which will re-position the div appended to the body.

Now when I set the LEFT css property of that appended div, the window.resize event get trigger for NO GOOD REASON.

It results in an infinite loop, triggering the window.resize again and again.

The code without fix:

$(window).resize(function(){    var onResize = function(){        //The method which alter some css properties triggers         //window.resize again and it ends in an infinite loop        someMethod();    }    window.clearTimeout(resizeTimeout);    resizeTimeout = window.setTimeout(onResize, 10);});

Solution:

var winWidth = $(window).width(),    winHeight = $(window).height();$(window).resize(function(){    var onResize = function(){        //The method which alter some css properties triggers         //window.resize again and it ends in an infinite loop        someMethod();    }    //New height and width    var winNewWidth = $(window).width(),        winNewHeight = $(window).height();    // compare the new height and width with old one    if(winWidth!=winNewWidth || winHeight!=winNewHeight){        window.clearTimeout(resizeTimeout);        resizeTimeout = window.setTimeout(onResize, 10);    }    //Update the width and height    winWidth = winNewWidth;    winHeight = winNewHeight;});

So basically it will check if the height or width is changed (which will happen ONLY when you actually resize with window).


this made sense to me and seems to work in IE7 and above:

    //variables to confirm window height and width    var lastWindowHeight = $(window).height();    var lastWindowWidth = $(window).width();    $(window).resize(function() {        //confirm window was actually resized        if($(window).height()!=lastWindowHeight || $(window).width()!=lastWindowWidth){            //set this windows size            lastWindowHeight = $(window).height();            lastWindowWidth = $(window).width();            //call my function            myfunction();        }    });


Bind your resize listener with .one() so that it unbinds itself after firing. Then you can do anything you want, so long as at the end you rebind the resize listener. I found the easiest way to do this is by putting the resize listener in an anonymous function like so:

var resizeListener = function(){  $(window).one("resize",function(){ //unbinds itself every time it fires    //resize things    setTimeout(resizeListener,100); //rebinds itself after 100ms  });}resizeListener();

You don't technically need the setTimeout wrapped around the resizeListener() but I'd threw it in there as a just-in-case and for some extra throttling.