Cross-browser window resize event – JavaScript / jQuery

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?

Solutions/Answers:

Solution 1:

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

Solution 2:

$(window).bind('resize', function () { 

    alert('resize');

});

Solution 3:

Here is the non-jQuery way of tapping into the resize event:

window.addEventListener('resize', function(event){
  // do stuff here
});

It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.

Solution 4:

Sorry to bring up an old thread, but if someone doesn’t want to use jQuery you can use this:

function foo(){....};
window.onresize=foo;

Solution 5:

Since you are open to jQuery, this plugin seems to do the trick.

Related:  How to upload image into HTML5 canvas

Solution 6:

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.