Skip to content

Instantly share code, notes, and snippets.

@HollyBang
Created March 4, 2019 08:45
Show Gist options
  • Select an option

  • Save HollyBang/159010c97fc4627e720ee2b59245a9fb to your computer and use it in GitHub Desktop.

Select an option

Save HollyBang/159010c97fc4627e720ee2b59245a9fb to your computer and use it in GitHub Desktop.
const offset = 100;
let xDown, yDown;
window.addEventListener('touchstart', e => {
const firstTouch = getTouch(e);
xDown = firstTouch.clientX;
yDown = firstTouch.clientY;
});
window.addEventListener('touchend', e => {
if (!xDown || !yDown) {
return;
}
const {
clientX: xUp,
clientY: yUp
} = getTouch(e);
const xDiff = xDown - xUp;
const yDiff = yDown - yUp;
const xDiffAbs = Math.abs(xDown - xUp);
const yDiffAbs = Math.abs(yDown - yUp);
// at least <offset> are a swipe
if (Math.max(xDiffAbs, yDiffAbs) < offset ) {
return;
}
if (xDiffAbs > yDiffAbs) {
if ( xDiff > 0 ) {
console.log('left');
} else {
console.log('right');
}
} else {
if ( yDiff > 0 ) {
console.log('up');
} else {
console.log('down');
}
}
});
function getTouch (e) {
return e.changedTouches[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment