public
Last active

Event delegation for JavaScript 'tap' events

  • Download Gist
Touch-Event-Delegation.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
var tapArea, moved, startX, startY;
 
tapArea = document.querySelector('#list'); //the area you want to capture taps
moved = false; //flags if the finger has moved once touchstart has fired
startX = 0; //starting x coordinate
startY = 0; //starting y coordinate
//capture touchstart
tapArea.ontouchstart = function(e) {
e.stopPropagation();
moved = false;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
};
 
//capture touchmove
tapArea.ontouchmove = function(e) {
//if the finger moves more than 10px flag to cancel the tap
//http://code.google.com/mobile/articles/fast_buttons.html
if (Math.abs(e.touches[0].clientX - startX) > 10 ||
Math.abs(e.touches[0].clientY - startY) > 10) {
moved = true;
}
};
 
//capture touchend
tapArea.ontouchend = function(e) {
e.preventDefault();
e.stopPropagation();
//get element from touch point
var element = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
//if the element is a text node, get its parent.
if (element.nodeType === 3) {
element = element.parentNode;
}
if (!moved) {
//check for the element type you want to capture
if (element.tagName.toLowerCase() === 'label') {
alert('tap');
}
}
};
 
//don't forget about touchcancel!
tapArea.ontouchcancel = function(e) {
//reset variables
moved = false;
startX = 0;
startY = 0;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.