Skip to content

Instantly share code, notes, and snippets.

@mattfysh
Created Dec 13, 2012
Embed
What would you like to do?
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