Skip to content

Instantly share code, notes, and snippets.

@aguilarcarlos
Last active February 24, 2024 13:52
Show Gist options
  • Save aguilarcarlos/a07f1cf82ecb9e8cc18daeb5feba0b7f to your computer and use it in GitHub Desktop.
Save aguilarcarlos/a07f1cf82ecb9e8cc18daeb5feba0b7f to your computer and use it in GitHub Desktop.
Swipe JS for Mobile App
/**
* @name _swipe
* Small event handler for swipe in mobile phones using javascript, this handler is based on http://stackoverflow.com/a/27115070
* This handler supports classes, ids and elements.
* @author David Aguilar
* @example
*
* _swipe("#element", function(dir, elem) {
* console.info("You're swiping to %s direction.", dir.type);
* });
*
* _swipe("#anotherElement", function(dir, elem) {
* if (dir.type === "up") {
* // do something
* }
* });
*
*/
var _swipe = function(element, fn) {
var swipe = {
sX: 0,
sY: 0,
eX: 0,
eY: 0
},
minX = 20,
maxX = 40,
minY = 40,
maxY = 50,
direction = null,
eventType = {
'up': {type: 'up', event: 'evt:swipe:up'},
'down': {type: 'down', event: 'evt:swipe:down'},
'left': {type: 'left', event: 'evt:swipe:left'},
'right': {type: 'right', event: 'evt:swipe:right'}
};
function getSelector(ele) {
var chars = {
'id': '#',
'class': '.'
};
if (ele.indexOf(chars.id) > -1) {
return document.getElementById(ele.substr(1));
} else if (ele.indexOf(chars.class) > -1) {
return document.getElementsByClassName(ele.substr(1));
} else {
return document.getElementsByTagName(ele);
}
}
function touchStartHandler (evt) {
var touches = evt.touches[0];
swipe.sX = touches.screenX;
swipe.sY = touches.screenY;
}
function touchMoveHandler (evt) {
evt.preventDefault();
var touches = evt.touches[0];
swipe.eX = touches.screenX;
swipe.eY = touches.screenY;
}
function touchEndHandler (evt) {
if (isHorizontal()) {
direction = swipe.eX > swipe.sX ? eventType.right : eventType.left;
} else {
direction = swipe.eY < swipe.sY ? eventType.up : eventType.down;
}
if (direction && typeof fn === 'function') {
fn(direction, element, evt);
return true;
}
}
function isHorizontal () {
var checkX = swipe.eX - minX > swipe.sX || swipe.eX + minX < swipe.sX,
checkY = swipe.eY < swipe.sY + maxY && swipe.sY > swipe.eY - maxY;
return checkX && checkY;
}
function isVertical () {
var checkY = swipe.eY - minY > swipe.sY || swipe.eY + minY < swipe.sY,
checkX = swipe.eX < swipe.sX + maxX && swipe.sX > swipe.eX - maxX;
return checkX && checkY;
}
function init (el) {
if (!el) {
console.warn('Coudn\'t be able to set listener to undefined element');
return;
}
el.addEventListener('touchstart', touchStartHandler, false);
el.addEventListener('touchmove', touchMoveHandler, false);
el.addEventListener('touchend', touchEndHandler, false);
}
init(getSelector(element));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment