Skip to content

Instantly share code, notes, and snippets.

@remy
Last active July 25, 2019 20:05
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 remy/0361b2b5d77c0b82535957ec88825cb4 to your computer and use it in GitHub Desktop.
Save remy/0361b2b5d77c0b82535957ec88825cb4 to your computer and use it in GitHub Desktop.
/**
* jQuery mousehold plugin - fires an event while the mouse is clicked down.
* Additionally, the function, when executed, is passed a single
* argument representing the count of times the event has been fired during
* this session of the mouse hold.
*
* @author Remy Sharp (leftlogic.com)
* @date 2006-12-15
* @example $("img").mousehold(200, function(i){ })
* @desc Repeats firing the passed function while the mouse is clicked down
*
* @name mousehold
* @type jQuery
* @param Number timeout The frequency to repeat the event in milliseconds
* @param Function fn A function to execute
* @cat Plugin
*/
jQuery.fn.mousehold = function(timeout, f) {
if (timeout && typeof timeout == 'function') {
f = timeout;
timeout = 100;
}
if (f && typeof f == 'function') {
var timer = 0;
var fireStep = 0;
return this.each(function() {
jQuery(this).mousedown(function() {
fireStep = 1;
var ctr = 0;
timer = setInterval(function() {
ctr++;
f.call(this, ctr);
fireStep = 2;
}, timeout);
})
clearMousehold = function() {
clearInterval(timer);
if (fireStep == 1) f.call(this, 1);
fireStep = 0;
}
jQuery(this).mouseout(clearMousehold);
jQuery(this).mouseup(clearMousehold);
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment