Created
July 6, 2011 19:38
-
-
Save alexgibson/1068146 to your computer and use it in GitHub Desktop.
Event delegation for JavaScript 'tap' events
This file contains hidden or 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
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cheeaun/tappable@08e844d :)