Skip to content

Instantly share code, notes, and snippets.

@EmmanuelBeziat
Created October 2, 2018 12:15
Show Gist options
  • Save EmmanuelBeziat/83eb7dde85c746c63c7662eb8bc3571e to your computer and use it in GitHub Desktop.
Save EmmanuelBeziat/83eb7dde85c746c63c7662eb8bc3571e to your computer and use it in GitHub Desktop.
Swipe left / right for mobile and desktop
el.addEventListener('touchstart', event => { start(event.touches[0].clientX, event.touches[0].clientY) }, false)
el.addEventListener('touchmove', event => { swipe(event.touches[0].clientX, event.touches[0].clientY) }, false)
el.addEventListener('mousedown', event => { start(event.clientX, event.clientY) }, false)
el.addEventListener('mousemove', event => { swipe(event.clientX, event.clientY) }, false)
let xDown = null
let yDown = null
function start (x, y) {
xDown = x
yDown = y
}
function swipe (xUp, yUp) {
if (!xDown || !yDown) return
const xDiff = xDown - xUp
const yDiff = yDown - yUp
if (Math.abs(xDiff) > Math.abs(yDiff)) {
// Left swipe
if (xDiff > 0) {
console.log('left')
}
// Right swipe
else {
console.log('right')
}
}
xDown = null
yDown = null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment