Created
January 21, 2012 14:35
-
-
Save asgeo1/1652946 to your computer and use it in GitHub Desktop.
doubletap event for jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); |
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. :)
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
I tried with .bind and this works but it wouldn't work with .delegate() or .on()
I tried it with Raul Sanchez's example except for the script part I changed it to