Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created October 27, 2016 13:32
Show Gist options
  • Save andreasvirkus/a700c5c6af2327937c4ecf053ed57bc3 to your computer and use it in GitHub Desktop.
Save andreasvirkus/a700c5c6af2327937c4ecf053ed57bc3 to your computer and use it in GitHub Desktop.
/**
* Just saving a solution by http://lehollandaisvolant.net/tout/examples/swipe/
* From http://stackoverflow.com/questions/2264072/detect-a-finger-swipe-through-javascript-on-the-iphone-and-android/23230280#23230280
*/
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
document.addEventListener('touchend', handleTouchEnd, false);
document.addEventListener('touchcancel', handleTouchEnd, false);
var xDown = null;
var yDown = null;
var doTouchBreak = null;
var minDelta = 200;
function handleTouchEnd() {
doTouchBreak = null;
};
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( !xDown || !yDown || doTouchBreak) { return; }
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
// horizontal swipe
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {
if ( xDiff > minDelta ) {
/* left swipe */
document.getElementById('info').appendChild(document.createTextNode('Left! '));
doTouchBreak = true;
} else if ( xDiff < -minDelta) {
/* right swipe */
document.getElementById('info').appendChild(document.createTextNode('Right! '));
doTouchBreak = true;
}
// vertical swipe
} else {
if ( yDiff > minDelta ) {
/* up swipe */
document.getElementById('info').appendChild(document.createTextNode('Up! '));
doTouchBreak = true;
} else if ( yDiff < -minDelta) {
/* down swipe */
document.getElementById('info').appendChild(document.createTextNode('Down! '));
doTouchBreak = true;
}
}
if (doTouchBreak) {
xDown = null;
yDown = null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment