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

Android - ImageView With Rounded Only One Corner

530 Valid Hostname Is Expected When Setting Up IIS 10 For Multiple Sites

Android - SetOnClickListener Vs OnClickListener Vs View.OnClickListener