Created
January 24, 2018 05:22
-
-
Save zettca/cbbbaf9b87c1404336bf52b5803a1649 to your computer and use it in GitHub Desktop.
Simple & Clean Javascript swipe direction detection
This file contains 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
const root = document.querySelector('body'); | |
const touchStart = { x: 0, y: 0 }; | |
root.addEventListener('touchstart', handleTouchStart, false); | |
root.addEventListener('touchend', handleTouchEnd, false); | |
function handleTouchStart(e) { | |
touchStart.x = e.changedTouches[0].screenX; | |
touchStart.y = e.changedTouches[0].screenY; | |
} | |
function handleTouchEnd(e) { | |
const dX = e.changedTouches[0].screenX - touchStart.x; | |
const dY = e.changedTouches[0].screenY - touchStart.y; | |
console.log(getDirection(dX, dY)); | |
} | |
function getDirection(dX, dY) { | |
if (dX === 0 && dY === 0) return 'TOUCH'; | |
if (Math.abs(dX) > Math.abs(dY)) { | |
return dX > 0 ? 'RIGHT' : 'LEFT'; | |
} else { | |
return dY > 0 ? 'DOWN' : 'UP'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment