Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery event touchclick
$.event.special.touchclick = {
setup : function(data) {
var elt = $(this);
elt.data($.extend({
sens : 25 // Available touch offset in pixels
}, data));
elt.bind("touchstart", $.event.special.touchclick.onTouchstart);
elt.bind("touchend", $.event.special.touchclick.onTouchend);
},
teardown : function() {
var elt = $(this);
elt.unbind("touchstart", $.event.special.touchclick.onTouchstart);
elt.unbind("touchend", $.event.special.touchclick.onTouchend);
},
onTouchstart : function(event) {
var elt = $(this);
elt.data("startPageX", event.originalEvent.touches[0].pageX);
elt.data("startPageY", event.originalEvent.touches[0].pageY);
},
onTouchend : function(event) {
var elt = $(this);
var diffX = Math.abs(event.originalEvent.changedTouches[0].pageX - elt.data("startPageX"));
var diffY = Math.abs(event.originalEvent.changedTouches[0].pageY - elt.data("startPageY"));
elt.data({
startPageX : null,
startPageY : null
});
var sens = elt.data("sens");
if (diffX < sens && diffY < sens /* FIXBUG OF TWICE FIRING */ && event.originalEvent["touches"].length == 0) {
event.preventDefault();
event.type = "touchclick";
$.event.dispatch.apply(this, arguments);
}
}
};
@comm1x

This comment has been minimized.

Copy link
Owner Author

@comm1x comm1x commented Aug 16, 2014

Usage

$("#root").on("touchclick", ".item", function() {
  // ...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment