Skip to content

Instantly share code, notes, and snippets.

@alexgibson
Created July 6, 2011 19:38
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexgibson/1068146 to your computer and use it in GitHub Desktop.
Save alexgibson/1068146 to your computer and use it in GitHub Desktop.
Event delegation for JavaScript 'tap' events
var tapArea, moved, startX, startY;
tapArea = document.querySelector('#list'); //the element to delegate
moved = false; //flags if the finger has moved
startX = 0; //starting x coordinate
startY = 0; //starting y coordinate
//touchstart
tapArea.ontouchstart = function(e) {
moved = false;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
};
//touchmove
tapArea.ontouchmove = function(e) {
//if the finger moves more than 10px flag to cancel the tap
//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;
}
};
//touchend
tapArea.ontouchend = function(e) {
e.preventDefault();
//get element from touch point
var element = e.changedTouches[0].target;
//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;
};
@cheeaun
Copy link

cheeaun commented Aug 17, 2011

@alexgibson
Copy link
Author

Zing! :)

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