Created
December 30, 2018 14:11
-
-
Save iliyaZelenko/64e1d7ed3fdeecf3aadc028f29524b4f to your computer and use it in GitHub Desktop.
An example of using swipe on mobile devices.
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
// at least 100 px are a swipe | |
// you can use the value relative to screen size: window.innerWidth * .1 | |
const offset = 100; | |
let xDown, yDown | |
window.addEventListener('touchstart', e => { | |
const firstTouch = getTouch(e); | |
xDown = firstTouch.clientX; | |
yDown = firstTouch.clientY; | |
}); | |
window.addEventListener('touchend', e => { | |
if (!xDown || !yDown) { | |
return; | |
} | |
const { | |
clientX: xUp, | |
clientY: yUp | |
} = getTouch(e); | |
const xDiff = xDown - xUp; | |
const yDiff = yDown - yUp; | |
const xDiffAbs = Math.abs(xDown - xUp); | |
const yDiffAbs = Math.abs(yDown - yUp); | |
// at least <offset> are a swipe | |
if (Math.max(xDiffAbs, yDiffAbs) < offset ) { | |
return; | |
} | |
if (xDiffAbs > yDiffAbs) { | |
if ( xDiff > 0 ) { | |
console.log('left'); | |
} else { | |
console.log('right'); | |
} | |
} else { | |
if ( yDiff > 0 ) { | |
console.log('up'); | |
} else { | |
console.log('down'); | |
} | |
} | |
}); | |
function getTouch (e) { | |
return e.changedTouches[0] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment