Skip to content

Instantly share code, notes, and snippets.

@pgaskin
Last active May 13, 2018 01:01
Show Gist options
  • Save pgaskin/36d9e3e8505e386ae3f4aba80e609c84 to your computer and use it in GitHub Desktop.
Save pgaskin/36d9e3e8505e386ae3f4aba80e609c84 to your computer and use it in GitHub Desktop.
Accurate and simple way to detect swipes in vanilla js.
let start = null
let end = null;
const el = document.body;
el.addEventListener('touchstart', event => start = event.changedTouches[0], false);
el.addEventListener('touchend', event => {
end = event.changedTouches[0];
let hr = (end.screenX - start.screenX) / el.getBoundingClientRect().width;
let vr = (end.screenY - start.screenY) / el.getBoundingClientRect().height;
if (hr > vr && hr > 0.25) return console.log('right');
if (hr < vr && hr < -0.25) return console.log('left');
if (vr > hr && vr > 0.25) return console.log('down');
if (vr < hr && vr < -0.25) return console.log('up');
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment