jQuery - lastclick special event
Using the awesome special events template from Ben Alman.
by mofle
HTML
<span>Click me</span>
<p id="click-event"></p>
CSS
body {
user-select: none;
-webkit-user-select: none;
-mox-user-select: none;
}
span {
background: #e6e6e6;
margin: 40px;
padding: 4px;
border: 1px solid #a7a7a7;
display: inline-block;
cursor: pointer;
user-select: none;
-webkit-user-select: none;
-mox-user-select: none;
}
JavaScript
(function($){
// A collection of elements to which the tripleclick event is bound.
var elems = $([]),
// Initialize the clicks counter and last-clicked timestamp.
clicks = 0,
timeout;
// Click speed threshold, defaults to 500.
$.lastclickThreshold = 500;
// Special event definition.
$.event.special.lastclick = {
setup: function(){
// Add this element to the internal collection.
elems = elems.add( this );
// If this is the first element to which the event has been bound,
// bind a handler to document to catch all 'click' events.
if ( elems.length === 1 ) {
$(document).on( 'click', click_handler );
}
},
teardown: function(){
// Remove this element from the internal collection.
elems = elems.not( this );
// If this is the last element removed, remove the document 'click'
// event handler that "powers" this special event.
if ( elems.length === 0 ) {
$(document).off( 'click', click_handler );
}
}
};
// This function is executed every time an element is clicked.
function click_handler( event ) {
var elem = $(event.target);
clearTimeout( timeout );
timeout = setTimeout(function() {
elem.trigger( 'lastclick', clicks );
clicks = 0;
}, $.lastclickThreshold );
clicks++;
}
$.fn.lastclick = function( data, callback ) {
return $(this).on( 'lastclick', data, callback );
};
})(jQuery);
$('span').lastclick(function( e, clicks ) {
console.log( 'lastclick', e, clicks );
$('#click-event').text( 'Clicks: ' + clicks );
});