Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Created December 13, 2012 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattfysh/4272960 to your computer and use it in GitHub Desktop.
Save mattfysh/4272960 to your computer and use it in GitHub Desktop.
Tap listener
window.utils = (function() {
function touch(el, type, listener) {
if (type === 'tap') {
var isDragging, startPos;
function touchStart(e) {
el.addEventListener('touchmove', touchMove);
el.addEventListener('touchend', touchEnd);
isDragging = false;
startPos = [e.touches[0].screenX, e.touches[0].screenY];
}
function touchMove(e) {
var movePos = [e.touches[0].screenX, e.touches[0].screenY],
distanceX = Math.abs(startPos[0] - movePos[0]),
distanceY = Math.abs(startPos[1] - movePos[1]),
distance = parseInt(Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2)), 10);
if (distance > 15) {
isDragging = true;
}
}
function touchEnd(e) {
el.removeEventListener('touchmove', touchMove);
el.removeEventListener('touchend', touchEnd);
if (!isDragging && listener) {
listener(e);
}
}
el.addEventListener('touchstart', touchStart);
}
}
function closest(el, selector) {
while (el) {
if (el.webkitMatchesSelector(selector)) {
return el;
}
el = el.parentElement;
}
}
/* export API */
return {
touch: touch,
closest: closest
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment