Created
June 26, 2019 11:37
-
-
Save HollyBang/df76eb52e27d89e8bd368e995f6ad10b to your computer and use it in GitHub Desktop.
Simple vanilla JS code swipe
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
| document.addEventListener('touchstart', handleTouchStart, false); | |
| document.addEventListener('touchmove', handleTouchMove, false); | |
| var xDown = null; | |
| var yDown = null; | |
| function getTouches(evt) { | |
| return evt.touches || // browser API | |
| evt.originalEvent.touches; // jQuery | |
| } | |
| function handleTouchStart(evt) { | |
| const firstTouch = getTouches(evt)[0]; | |
| xDown = firstTouch.clientX; | |
| yDown = firstTouch.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