Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Zepto's touch.js but working with jQuery and also removing the 300ms delay
// ************************************************************************
// You shouldn't use this anymore.
// http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away
//
// Basically, disable double tap to zoom in on sites on a mobile device.
// <meta name="viewport" content="width=device-width">
//
// If you want to also disable pinch-zooming
// <meta name="viewport" content="width=device-width, user-scalable=no">
//
// Done!
// ************************************************************************
// If you really want to see the old code, its below.
// Adding a modified version of touch.js as a plug-in from Zepto into jQuery
// This will remove the 300ms delay before firing a click event... got rid of double tap support (Who uses that?)
// Also still has support for longpress.
// https://github.com/madrobby/zepto/blob/master/src/touch.js#files
(function($){
var touch = {}, longTapTimeout, longTapDelay = 750;
function parentIfText(node) {
return node.hasOwnProperty('tagName') ? node : node.parentNode;
}
function longTap() {
longTapTimeout = null;
if (touch.last) {
$(touch.target).trigger('longtap');
touch = {};
}
}
function cancelLongTap() {
if (longTapTimeout) {
clearTimeout(longTapTimeout);
}
longTapTimeout = null;
}
function cancelAll() {
if (longTapTimeout) {
clearTimeout(longTapTimeout);
}
longTapTimeout = null;
touch = {};
}
$(document).ready(function () {
$(document.body).bind('touchstart', function (e) {
touch = {};
var now = Date.now();
touch.target = parentIfText(e.originalEvent.touches[0].target);
touch.x1 = e.originalEvent.touches[0].pageX;
touch.y1 = e.originalEvent.touches[0].pageY;
touch.last = now;
longTapTimeout = setTimeout(longTap, longTapDelay);
}).bind('touchmove', function (e) {
cancelLongTap();
touch.x2 = e.originalEvent.touches[0].pageX;
touch.y2 = e.originalEvent.touches[0].pageY;
}).bind('touchend', function (e) {
cancelLongTap();
if ((touch.x2 > 0 || touch.y2 > 0) &&
(Math.abs(touch.x1 - touch.x2) > 30 || Math.abs(touch.y1 - touch.y2) > 30)) {
// Swipe Event
touch = {};
} else if (touch.hasOwnProperty('last')) {
// Tap Event
$(touch.target).trigger('tap');
}
touch = {};
}).bind('touchcancel', cancelAll).bind('click', function (e) {
// e.stopPropagation();
});
['tap', 'longtap'].forEach(function (m) {
$.fn[m] = function (callback) {
return this.bind(m, callback);
};
});
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment