BuddyJoe BuddyJoe - 7 months ago 40
Javascript Question

Cross-browser window resize event - JavaScript / jQuery

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

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);
});