Skip to content

Instantly share code, notes, and snippets.

@creage
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creage/11302400 to your computer and use it in GitHub Desktop.
Save creage/11302400 to your computer and use it in GitHub Desktop.
jQuery.ondelay
(function ($, window, document, undefined) {
$.fn.extend({
/*
* Provides event handling with delaying ability
* respects two attributes coming as data attributes:
* timeout: integer value of ms to timeout before event will be triggered once event is stopped to be fired
* throttle: boolean, default false
* if set to true - event will be fired once per timeout,
* if set to false - event will be fired only after timeout starting from event is stoped firing
*/
ondelay: function (type, selector, data, fn) {
var timeout = 0,
throttle = false;
if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === 'string') {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (!!data && data.timeout) timeout = data.timeout;
if (!!data && data.throttle) throttle = data.throttle;
// Allow delayed function to be removed with fn in unbind function
fn.guid = fn.guid || ($.guid && $.guid++);
// Bind each separately so that each element has its own delay
return this.each(function () {
var wait = null;
function cb() {
var e = $.extend(true, {}, arguments[0]),
ctx = this,
throttler = function () {
wait = null;
try {
fn.call(ctx, e, ctx.nodeType/* try to access element property, non-existing elements will fail in IE8 */);
} catch (_e) {
// fn is no longer available
if (_e.number != -2146823277 && _e.number != -2146828218) throw _e;
}
};
if (!throttle) { clearTimeout(wait); wait = null; }
if (!wait) { wait = setTimeout(throttler, timeout); }
}
cb.guid = fn.guid;
$(this).on(type, selector, data, cb);
});
}
});
}(jQuery, window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment