jQuery special events
Custom tripleclick event: per-handler threshold http://benalman.com/news/2010/03/jquery-special-events/
by Ben Alman
HTML
<h1>
<a href="http://benalman.com/news/2010/03/jquery-special-events/" target="_top">jQuery special events</a>
» Custom tripleclick event: per-handler threshold
</h1>
<p class="intro">(triple-click boxes)</p>
<div id="test">
<div id="a">
a
<div id="b">b</div>
<div id="c">c</div>
<div id="d">d</div>
</div>
</div>
<div id="nav">
<a href="#">clear log</a>
</div>
<div id="log"></div>
CSS
body { font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; }
h1 { font-weight: 700; font-family: "Gill Sans", "Gill Sans MT", Arial, Helvetica, sans-serif; }
h1, a { color: #913D00; }
a:hover { color: #FF7F00; }
h1 { font-size: 120%; margin-bottom: 0.6em; }
.intro { font-style: italic; margin-top: 0.5em; }
#test div {
border: 1px solid #000;
margin: 1em 0;
padding: 0.5em 1em;
}
#a {
padding-bottom: 0 !important;
}
#log {
margin-top: 1em;
}
JavaScript
$(function(){
function log(){
$('#log').append([].join.call(arguments,', ')+'<br/>');
};
$('#test div').bind( 'tripleclick', 1000, function(event){
log( '1. #' + this.id, 1000 );
//return false; // This won't work, propagation can't be stopped.
//event.stopPropagation(); // This won't work, propagation can't be stopped.
//event.stopImmediatePropagation(); // Un-comment to stop immediate propagation.
});
$('#test div').bind( 'tripleclick', 250, function(event){
log( '2. #' + this.id, 250 );
});
// This is just for the "clear log" link.
$('a').click(function(){
$('#log').empty();
return false;
});
});
//////////////////////////////////////////////////
// THE FOLLOWING CODE IS TAKEN FROM THE EXAMPLE //
//////////////////////////////////////////////////
(function($){
// Click speed threshold, defaults to 500.
$.tripleclickThreshold = 500;
// Special event definition.
$.event.special.tripleclick = {
setup: function( data ) {
// When the event is first bound, bind the "click" event handler that
// will be used to power the custom "tripleclick" event.
$(this).bind( 'click', click_handler );
},
teardown: function() {
// When the last event is unbound, unbind the "click" event handler.
$(this).unbind( 'click', click_handler );
},
add: function( handleObj ){
// The event handler being bound to the event.
var old_handler = handleObj.handler,
// Initialize this handler's clicks counter and last-clicked
// timestamp.
clicks = 0,
last = 0;
// When the event is triggered, instead of executing the bound
// handler directly, `handleObj.handler` will be called, which will
// then call the original `old_handler` function. Notice that an extra
// argument is being passed to the new_handler function, see the
...