Fire Resize Event Once Not Based On Timing
Is it possible to avoid twice firing events by browsers, but not based on timing (in case your resize event execution lasts long that solution is bad)
Solution 1:
window.blockResize = false;
$(window).resize(function() {
if (window.blockResize) return;
//do stuff
window.blockResize = true;
setTimeout(function(){window.blockResize = false},200);
});
Ok, it's still based on timers, but It works in my case now.
Solution 2:
You can use setTimeout()
and clearTimeout()
in conjunction with jQuery.data
:
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
Update
I wrote an extension to enhance jQuery's default on
(& bind
)-event-handler. It attaches an event handler function for one or more events to the selected elements if the event was not triggered for a given interval. This is useful if you want to fire a callback only after a delay, like the resize event, or else.
https://github.com/yckart/jquery.unevent.js
;(function ($) {
var methods = { on: $.fn.on, bind: $.fn.bind };
$.each(methods, function(k){
$.fn[k] = function () {
var args = [].slice.call(arguments),
delay = args.pop(),
fn = args.pop(),
timer;
args.push(function () {
var self = this,
arg = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(self, [].slice.call(arg));
}, delay);
});
return methods[k].apply(this, isNaN(delay) ? arguments : args);
};
});
}(jQuery));
Use it like any other on
or bind
-event handler, except that you can pass an extra parameter as a last:
$(window).on('resize', function(e) {
console.log(e.type + '-event was 200ms not triggered');
}, 200);
Post a Comment for "Fire Resize Event Once Not Based On Timing"