Cross-browser window resize event - JavaScript / jQuery Cross-browser window resize event - JavaScript / jQuery javascript javascript

Cross-browser window resize event - JavaScript / jQuery


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


$(window).bind('resize', function () {     alert('resize');});


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.