Skip to content

Instantly share code, notes, and snippets.

@jimmykhlam
Created November 26, 2011 22:18
Show Gist options
  • Save jimmykhlam/1396394 to your computer and use it in GitHub Desktop.
Save jimmykhlam/1396394 to your computer and use it in GitHub Desktop.
Modifying jQuery mousehold event plugin to pass through original mousedown event
/*
* 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
*
* Modified by Jimmy Lam (jimmykhlam.com) on 2011-11-26 to include passing
* the origEv event from original mousedown.
*/
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() {
var origEv; //var for original event
jQuery(this).mousedown(function(ev) {
origEv = ev; //rem original event
fireStep = 1;
var ctr = 0;
var t = this;
timer = setInterval(function() {
ctr++;
f.call(t, ctr, ev);
fireStep = 2;
}, timeout);
})
clearMousehold = function() {
clearInterval(timer);
if (fireStep == 1) f.call(this, 1, origEv); //pass original event
fireStep = 0;
}
jQuery(this).mouseout(clearMousehold);
jQuery(this).mouseup(clearMousehold);
})
}
}
@breve
Copy link

breve commented Mar 13, 2012

Hi Jimmy, looks like this is just what I was looking for. But I don't know how to invoke origEv after call to mousehold. I mean, if call is like:
$(selector).mousehold(timeout, function(i){ ... })

Then how do I use origEv inside function(i) ?

@breve
Copy link

breve commented Mar 13, 2012

Or let me rephrase: how to keep track of mousehold event's properties like pageX and pageY, if they are changed during mousehold?

Because event always returns values from beginning of mousehold.

@jimmykhlam
Copy link
Author

Hi Breve, access origEv like so: mousehold(timeout, function(ctr, ev){ ... }) //ev is the origEv

Hope it helps.

@breve
Copy link

breve commented Mar 27, 2012

Thanks Jimmy, that is it.

@arthur12345543
Copy link

Thanks Jimmy. Nice library, today she is safe my time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment