Skip to content

Instantly share code, notes, and snippets.

@Tivoli
Last active August 4, 2016 09:03
Show Gist options
  • Save Tivoli/cce7e1a2a12a2b7fa436 to your computer and use it in GitHub Desktop.
Save Tivoli/cce7e1a2a12a2b7fa436 to your computer and use it in GitHub Desktop.
Javascript Swipe Events
function getSwipeEvent(deltaX, deltaY) {
switch(true) {
case deltaX >= 50: return new Event('swipeLeft');
case deltaX <= -50: return new Event('swipeRight');
case deltaY >= 50: return new Event('swipeUp');
case deltaY <= -50: return new Event('swipeDown');
}
}
function swipeEvents() {
var startX, startY;
function touchstart(event) {
var touches = event.touches;
if (touches && touches.length) {
startX = touches[0].pageX;
startY = touches[0].pageY;
document.addEventListener('touchmove', touchmove);
}
}
document.addEventListener('touchstart', touchstart);
function touchmove(event) {
var touches = event.touches;
if (touches && touches.length) {
event.preventDefault();
var
deltaX = startX - touches[0].pageX,
deltaY = startY - touches[0].pageY,
swipeEvent = getSwipeEvent(deltaX, deltaY);
if (swipeEvent) document.dispatchEvent(swipeEvent);
if (Math.abs(deltaX) >= 50 || Math.abs(deltaY) >= 50) {
document.removeEventListener('touchmove', touchmove);
}
}
}
};
swipeEvents();
document.addEventListener("swipeDown", function(event) {
event.preventDefault();
moveUp();
});
document.addEventListener("swipeUp", function(event){
event.preventDefault();
moveDown();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment