Last active
June 20, 2017 19:05
-
-
Save mcansh/380b9e948655a273dde8fd7e42056201 to your computer and use it in GitHub Desktop.
swipe detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let xDown = null; | |
let yDown = null; | |
function handleTouchStart(e) { | |
xDown = e.touches[0].clientX; | |
yDown = e.touches[0].clientY; | |
} | |
function handleTouchMove(e) { | |
if (!xDown || !yDown) { | |
return; | |
} | |
const xUp = e.touches[0].clientX; | |
const yUp = e.touches[0].clientY; | |
const xDiff = xDown - xUp; | |
const yDiff = yDown - yUp; | |
if (Math.abs(xDiff) > Math.abs(yDiff)) { | |
if (xDiff > 0) { | |
// left swipe | |
console.log('left'); | |
} else { | |
// right swipe | |
console.log('right'); | |
} | |
} else { | |
if (yDiff > 0) { | |
// up swipe | |
console.log('up'); | |
} else { | |
// down swipe | |
console.log('down'); | |
} | |
} | |
// reset values | |
xDown = null; | |
yDown = null; | |
} | |
document.addEventListener('touchstart', handleTouchStart, { passive: true }); | |
document.addEventListener('touchmove', handleTouchMove, { passive: true }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment