Skip to content

Instantly share code, notes, and snippets.

@mcansh
Last active June 20, 2017 19:05
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 mcansh/380b9e948655a273dde8fd7e42056201 to your computer and use it in GitHub Desktop.
Save mcansh/380b9e948655a273dde8fd7e42056201 to your computer and use it in GitHub Desktop.
swipe detection
let xDown = null;
let yDown = null;
function handleTouchStart(e) {
xDown = e.touches[0].clientX;
yDown = e.touches[0].clientY;
}
function handleTouchMove(e) {
if (!xDown || !yDown) {
return;
}
const xUp = e.touches[0].clientX;
const yUp = e.touches[0].clientY;
const xDiff = xDown - xUp;
const yDiff = yDown - yUp;
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0) {
// left swipe
console.log('left');
} else {
// right swipe
console.log('right');
}
} else {
if (yDiff > 0) {
// up swipe
console.log('up');
} else {
// down swipe
console.log('down');
}
}
// reset values
xDown = null;
yDown = null;
}
document.addEventListener('touchstart', handleTouchStart, { passive: true });
document.addEventListener('touchmove', handleTouchMove, { passive: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment