jQuery special events
Custom tripleclick event: per-element threshold http://benalman.com/news/2010/03/jquery-special-events/
by bizamajig
HTML
<h1>
<a href="http://benalman.com/news/2010/03/jquery-special-events/" target="_top">jQuery special events</a>
» Custom tripleclick event: per-element 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, initialize the element plugin data
// (including clicks counter, last-clicked timestamp, and a threshold
// value if specified), and bind the "click" event handler that will
// be used to power the custom "tripleclick" event.
$(this)
.data( 'tripleclick', { clicks: 0, last: 0, threshold: data })
.bind( 'click', click_handler );
},
teardown: function() {
// When the last event is unbound, remove all element plugin data and
// unbind the "click" event handler.
$(this)
.removeData( 'tripleclick' )
.unbind( 'click', click_handler );
}
};
// This function is executed every time an element is clicked.
function click_handler( event ) {
var elem = $(this),
// Get plugin data stored on the element.
data = elem.data( 'tripleclick' ),
// Use the...