Skip to content

Instantly share code, notes, and snippets.

@AndrewYatzkan
Created July 25, 2018 22:03
Show Gist options
  • Save AndrewYatzkan/778edd1f2360787ab5b4e0bb03009613 to your computer and use it in GitHub Desktop.
Save AndrewYatzkan/778edd1f2360787ab5b4e0bb03009613 to your computer and use it in GitHub Desktop.
Simple and short swipe direction detection in vanilla js
var last={x: null,y: null};
document.addEventListener("touchstart", e => {
let touch = e.touches[0];
last.x = touch.clientX;
last.y = touch.clientY;
});
document.addEventListener("touchend", e => {
let touch = e.changedTouches[0];
let diff = {x:last.x-touch.clientX,y:last.y-touch.clientY};
if (Math.abs(diff.x) > Math.abs(diff.y)) {
if (diff.x > 0) {
// left
} else {
// right
}
} else {
if (diff.y > 0) {
// up
} else {
// down
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment