Skip to content

Instantly share code, notes, and snippets.

@anderskristo
Created September 15, 2017 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anderskristo/99944c4229477aa54be59d3fd4cfdc7d to your computer and use it in GitHub Desktop.
Save anderskristo/99944c4229477aa54be59d3fd4cfdc7d to your computer and use it in GitHub Desktop.
/**
* Mobile swipe
*/
var swipeFunc = {
touches: {
"touchstart": {"x": -1, "y": -1},
"touchmove": {"x": -1, "y": -1},
"touchend": false,
"direction": "undetermined"
},
touchHandler: function(event) {
var touch;
if (typeof event !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart' :
case 'touchmove' :
swipeFunc.touches[event.type].x = touch.pageX;
swipeFunc.touches[event.type].y = touch.pageY;
break;
case 'touchend' :
swipeFunc.touches[event.type] = true;
if (swipeFunc.touches.touchstart.x > -1 && swipeFunc.touches.touchmove.x > -1) {
swipeFunc.touches.direction = swipeFunc.touches.touchstart.x < swipeFunc.touches.touchmove.x ? 'right' : 'left';
console.log(swipeFunc.touches[event.type].x);
// Do stuff
if (swipeFunc.touches.direction === 'left') {
swipeFunc.swipeLeft(event);
} else if (swipeFunc.touches.direction === 'right') {
swipeFunc.swipeRight(event);
} else {
console.log('[SWIPE] no swipe');
}
}
default :
break;
}
}
},
swipeLeft: function(event) {
var target = event.target;
var parent = event.target.offsetParent
// Remove all active
var els = document.getElementsByClassName('is-swiped');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('is-swiped');
}
// Add active on target
if (parent.classList.contains('home-mobile-menu')) {
target.classList.add('is-swiped');
}
},
swipeRight: function(event) {
var target = event.target;
var parent = event.target.offsetParent.offsetParent;
// Remove active on target
if (parent.classList.contains('is-swiped')) {
parent.classList.remove('is-swiped');
}
},
init: function() {
document.addEventListener('touchstart', swipeFunc.touchHandler, false);
document.addEventListener('touchmove', swipeFunc.touchHandler, false);
document.addEventListener('touchend', swipeFunc.touchHandler, false);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment