Cross-browser Window Resize Event - JavaScript / JQuery


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


$(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.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable