Cross-browser window resize event - JavaScript / jQuery

BuddyJoe picture BuddyJoe · Mar 1, 2009 · Viewed 266.2k times · Source

What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?

And can you turn both scrollbars on/off?

Answer

Andrew Hedges picture Andrew Hedges · Jun 3, 2010

jQuery has a built-in method for this:

$(window).resize(function () { /* do something */ });

For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:

function doSomething() {
    alert("I'm done resizing for the moment");
};

var resizeTimer;
$(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(doSomething, 100);
});