Detect Click Type
Check if single or double click function
by Paul Leech
HTML
<button>Click Me!</button>
<br /><br />
<footer>
<strike>Derived</strike> <em>Slightly</em> modified from: <a href="https://gist.github.com/ncr/399624">https://gist.github.com/ncr/399624</a><br />
</footer>
CSS
button {
border-radius: 5px;
background: rgba(250, 0, 0, 0.75);
color: #eee;
outline: none;
padding: 5px;
font-size: 1.25rem;
}
body { font-family: sans-serif;font-size: 12px; }
footer { position: fixed; bottom:10px; }
.single { background: rgba(150,0,0,0.75); }
.double { background: rgba(50, 0, 0, 0.75); }
JavaScript
jQuery.fn.click_type = 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 || 400);
}
});
});
}
$("button").click_type(function() {
//alert("Try double-clicking me!")
$(this).text('SINGLE Clicked!');
//$('button').class('single');
}, function() {
//alert("Double click detected, I'm hiding")
$(this).text('DOUBLE Clicked!');
//$('button').class('double');
});