Skip to content

Instantly share code, notes, and snippets.

@john-lemon
Created October 8, 2015 12:55
Show Gist options
  • Select an option

  • Save john-lemon/dd50d114b3e5ad34e251 to your computer and use it in GitHub Desktop.

Select an option

Save john-lemon/dd50d114b3e5ad34e251 to your computer and use it in GitHub Desktop.
Detect swipe event on pure js
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment