Last active
August 4, 2016 17:41
-
-
Save mCzolko/bdd64410554a0f21cfd47dc37b56f109 to your computer and use it in GitHub Desktop.
Swipe javascript handler
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('touchmove', handleTouchMove, false) | |
document.addEventListener('touchend', handleTouchEnd, false) | |
class Position { | |
constructor(x, y) { | |
this.x = x | |
this.y = y | |
} | |
getX() { | |
return this.x | |
} | |
getY() { | |
return this.y | |
} | |
diffX(pos) { | |
return pos.x - this.x | |
} | |
diffY(pos) { | |
return pos.y - this.y | |
} | |
diff(pos) { | |
return new Position( | |
this.diffX(pos), | |
this.diffY(pos) | |
) | |
} | |
distance(pos) { | |
return Math.sqrt( | |
Math.pow(pos.getX() - this.getX(), 2) + | |
Math.pow(pos.getY() - this.getY(), 2) | |
) //euclidian distance | |
} | |
} | |
var firstPosition = null | |
var lastPosition = null | |
function reset() { | |
firstPosition = null | |
lastPosition = null | |
} | |
function handleTouchMove(evt) { | |
if (firstPosition) { | |
lastPosition = getPosition(evt) | |
document.dispatchEvent(new CustomEvent('swipemove', { | |
detail: { position: lastPosition } | |
})) | |
} else { | |
firstPosition = getPosition(evt) | |
document.dispatchEvent(new CustomEvent('swipestart', { | |
detail: { position: firstPosition } | |
})) | |
} | |
} | |
function handleTouchEnd(evt) { | |
if ( ! firstPosition && ! lastPosition ) return // click or tap | |
handleSwipe(firstPosition, lastPosition) | |
document.dispatchEvent(new CustomEvent('swipeend', { detail: { | |
firstPosition: firstPosition, | |
lastPosition: lastPosition | |
}})) | |
reset() | |
} | |
function handleSwipe(first, last) { | |
const xDiff = last.diffX(first) | |
const yDiff = last.diffY(first) | |
var swipeDirection = 'right' | |
if (Math.abs(xDiff) > Math.abs(yDiff)) { | |
if (xDiff > 0) { | |
swipeDirection = 'left' | |
} | |
} else { | |
if (yDiff > 0) { | |
swipeDirection = 'up' | |
} else { | |
swipeDirection = 'down' | |
} | |
} | |
document.dispatchEvent(new CustomEvent(swipeDirection, { detail: { | |
firstPosition: first, | |
lastPosition: last | |
}})) | |
} | |
function getPosition(evt) { | |
return new Position(evt.touches[0].clientX, evt.touches[0].clientY) | |
} | |
document.addEventListener('swipestart', function(e) { console.log(e) }, false) | |
document.addEventListener('swipemove', function(e) { console.log(e) }, false) | |
document.addEventListener('swipeend', function(e) { console.log(e) }, false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment