Skip to content

Instantly share code, notes, and snippets.

@asgeo1
Created January 21, 2012 14:35
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save asgeo1/1652946 to your computer and use it in GitHub Desktop.
Save asgeo1/1652946 to your computer and use it in GitHub Desktop.
doubletap event for jquery
//based on blog post that I saw here: http://www.sanraul.com/2010/08/01/implementing-doubletap-on-iphones-and-ipads/
(function($){
$.fn.doubletap = function(fn) {
return fn ? this.bind('doubletap', fn) : this.trigger('doubletap');
};
$.attrFn.doubletap = true;
$.event.special.doubletap = {
setup: function(data, namespaces){
$(this).bind('touchend', $.event.special.doubletap.handler);
},
teardown: function(namespaces){
$(this).unbind('touchend', $.event.special.doubletap.handler);
},
handler: function(event){
var action;
clearTimeout(action);
var now = new Date().getTime();
//the first time this will make delta a negative number
var lastTouch = $(this).data('lastTouch') || now + 1;
var delta = now - lastTouch;
var delay = delay == null? 500 : delay;
if(delta < delay && delta > 0){
// After we detct a doubletap, start over
$(this).data('lastTouch', null);
// set event type to 'doubletap'
event.type = 'doubletap';
// let jQuery handle the triggering of "doubletap" event handlers
$.event.handle.apply(this, arguments);
}else{
$(this).data('lastTouch', now);
action = setTimeout(function(evt){
// set event type to 'doubletap'
event.type = 'tap';
// let jQuery handle the triggering of "doubletap" event handlers
$.event.handle.apply(this, arguments);
clearTimeout(action); // clear the timeout
}, delay, [event]);
}
}
};
})(jQuery);
@enzi
Copy link

enzi commented Apr 22, 2013

Thanks for the script!

I had a weird bug on the iPad where the first double tap was fine and after that every tap triggered a double tap. The problem was that I'm using multi touch and the timer event gets therefore duplicated.

What I did to fix this was rebinding the event to 'touchstart' instead of 'touchend' and then

if (event.targetTouches.length <= 1) {
// rest of the handler code
}

So, if anyone has multi touch support and runs into this you know what to do. :)

@VigibotDev
Copy link

There is no multitouch filter ? (distance from two tap)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment