Detect Window Resize using jQuery the correct way.
jQuery $(window).resize
fires multiple times while you are still resizing the window. In order to avoid calling a heavy function on resize use the following snippet.
The following code calls yourFunctionHere()
only every 500 milliseconds while the user is resizing the window. Provide a unique string instead of "UNIQUE_ID"
every time you use this function.
$(window).resize(function () {
finalEvent(function(){
yourFunctionHere();
},500,"UNIQUE_ID") // provide unique string as ID
});
// Resize helper check for final event
var finalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "I_need_unique_ID";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
Cheers!