How to differentiate single click event and double click event?
Solution 1:
The behavior of the dblclick
event is explained at Quirksmode.
The order of events for a dblclick
is:
- mousedown
- mouseup
- click
- mousedown
- mouseup
- click
- dblclick
The one exception to this rule is (of course) Internet Explorer with their custom order of:
- mousedown
- mouseup
- click
- mouseup
- dblclick
As you can see, listening to both events together on the same element will result in extra calls to your click
handler.
Solution 2:
You need to use a timeout to check if there is an another click after the first click.
Here is the trick:
// Author: Jacek Becela
// Source: http://gist.github.com/399624
// License: MIT
jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
return this.each(function(){
var clicks = 0, self = this;
jQuery(this).click(function(event){
clicks++;
if (clicks == 1) {
setTimeout(function(){
if(clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 300);
}
});
});
}
Usage:
$("button").single_double_click(function () {
alert("Try double-clicking me!")
}, function () {
alert("Double click detected, I'm hiding")
$(this).hide()
})
<button>Click Me!</button>
EDIT:
As stated below, prefer using the native dblclick
event: http://www.quirksmode.org/dom/events/click.html
Or the one provided by jQuery: http://api.jquery.com/dblclick/