Last active
January 20, 2020 07:18
-
-
Save dominictobias/e7e44d49ad41b849ccfaf909a7154fd7 to your computer and use it in GitHub Desktop.
Native JS 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 startX = 0; | |
let startY = 0; | |
function handleTouchStart(e) { | |
startX = e.changedTouches[0].screenX; | |
startY = e.changedTouches[0].screenY; | |
} | |
function handleTouchEnd(e) { | |
const diffX = e.changedTouches[0].screenX - startX; | |
const diffY = e.changedTouches[0].screenY - startY; | |
const ratioX = Math.abs(diffX / diffY); | |
const ratioY = Math.abs(diffY / diffX); | |
const absDiff = Math.abs(ratioX > ratioY ? diffX : diffY); | |
// Ignore small movements. | |
if (absDiff < 30) { | |
return; | |
} | |
if (ratioX > ratioY) { | |
if (diffX >= 0) { | |
console.log('right swipe'); | |
} else { | |
console.log('left swipe'); | |
} | |
} else { | |
if (diffY >= 0) { | |
console.log('down swipe'); | |
} else { | |
console.log('up swipe'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment