Skip to content

Instantly share code, notes, and snippets.

@ryancat
Created September 12, 2017 06:25
Show Gist options
  • Save ryancat/1bd83401f5e6c833c75f49de2fe71b77 to your computer and use it in GitHub Desktop.
Save ryancat/1bd83401f5e6c833c75f49de2fe71b77 to your computer and use it in GitHub Desktop.
Mobile touch move detection
let touches = {
touchstart: Object.assign({}, {
x: -1,
y: -1
}),
touchmove: Object.assign({}, {
x: -1,
y: -1
})
}
function handleTouch (evt) {
if (typeof evt.touches === 'undefined') {
return
}
let touch = evt.touches[0]
switch (evt.type) {
case 'touchstart':
case 'touchmove':
touches[evt.type].x = touch.pageX
touches[evt.type].y = touch.pageY
break
case 'touchend': {
if (touches.touchstart.x > -1 && touches.touchmove.x > -1) {
let dx = touches.touchmove.x - touches.touchstart.x,
dy = touches.touchmove.y - touches.touchstart.y
if (Math.abs(dx) > Math.abs(dy)) {
// Horizontal move
if (dx > 0) {
// Move right
}
else {
// Move left
}
}
else {
// Vertical move
if (dy > 0) {
// Move down
}
else {
// Move up
}
}
}
break
}
}
}
document.addEventListener('touchstart', handleTouch)
document.addEventListener('touchmove', handleTouch)
document.addEventListener('touchend', handleTouch)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment