Skip to content

Instantly share code, notes, and snippets.

@dominictobias
Last active January 20, 2020 07:18
Show Gist options
  • Save dominictobias/e7e44d49ad41b849ccfaf909a7154fd7 to your computer and use it in GitHub Desktop.
Save dominictobias/e7e44d49ad41b849ccfaf909a7154fd7 to your computer and use it in GitHub Desktop.
Native JS swipe detection
let startX = 0;
let startY = 0;
function handleTouchStart(e) {
startX = e.changedTouches[0].screenX;
startY = e.changedTouches[0].screenY;
}
function handleTouchEnd(e) {
const diffX = e.changedTouches[0].screenX - startX;
const diffY = e.changedTouches[0].screenY - startY;
const ratioX = Math.abs(diffX / diffY);
const ratioY = Math.abs(diffY / diffX);
const absDiff = Math.abs(ratioX > ratioY ? diffX : diffY);
// Ignore small movements.
if (absDiff < 30) {
return;
}
if (ratioX > ratioY) {
if (diffX >= 0) {
console.log('right swipe');
} else {
console.log('left swipe');
}
} else {
if (diffY >= 0) {
console.log('down swipe');
} else {
console.log('up swipe');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment