Skip to content

Instantly share code, notes, and snippets.

@kaspereden
Last active October 31, 2017 09:31
Show Gist options
  • Save kaspereden/ff105c628c0c537fde820f6e5f845a7e to your computer and use it in GitHub Desktop.
Save kaspereden/ff105c628c0c537fde820f6e5f845a7e to your computer and use it in GitHub Desktop.
version 1 of siwper
/**
* Swiper module
*
* It performs the callback function and returns the swipe direction
*/
class Swiper {
constructor() {
// minimal swiping minDistance
this.minDistance = 100;
// required min time allowed to travel that distance
this.minTime = 99;
// maximum time allowed to travel that distance to avoid really slow swiping
this.maxTime = 250;
}
init(element, callback, preventScroll = false) {
this.elem = element;
this.preventScroll = preventScroll;
this.callback = callback;
this.configureSwipe();
}
configureSwipe() {
let startX,
startY,
distance,
elapsedTime,
startTime;
this.elem.addEventListener('touchstart', (e) => {
let changedTouch = e.changedTouches[0];
distance = 0;
startTime = new Date().getTime();
startX = changedTouch.pageX;
startY = changedTouch.pageY;
if (this.preventScroll) {
e.preventDefault();
}
}, false);
if (this.preventScroll) {
this.elem.addEventListener('touchmove', (e) => {
e.preventDefault();
}, false);
}
this.elem.addEventListener('touchend', (e) => {
let changedTouch = e.changedTouches[0];
let swipeDirection = Swiper.STATUS.NO_SWIPE;
distance = changedTouch.pageX - startX;
elapsedTime = new Date().getTime() - startTime;
// Check for the validity of whether or not an actual swipe occurred
// before going into the direction details.
if (this.validateSwipe(elapsedTime, startY, changedTouch.pageY)) {
swipeDirection = this.getSwipeDirection(distance);
}
this.callback(swipeDirection);
if (this.preventScroll) {
e.preventDefault();
}
}, false)
}
getSwipeDirection(distance) {
const STATUS = Swiper.STATUS;
if (distance >= this.minDistance) {
return STATUS.SWIPE_RIGHT;
} else if (distance < ( this.minDistance * -1)) {
return STATUS.SWIPE_LEFT;
}
return status.TOO_SHORT;
}
validateSwipe(elapsedTime, pageY, startY) {
return elapsedTime <= this.maxTime && elapsedTime > this.minTime && Math.abs(pageY - startY) <= 100;
}
static isLeftSwipe(direction) {
return direction === Swiper.STATUS.SWIPE_LEFT;
}
static isRightSwipe(direction) {
return direction === Swiper.STATUS.SWIPE_RIGHT;
}
static get STATUS() {
return {
SWIPE_LEFT: 'SWIPE_LEFT',
SWIPE_RIGHT: 'SWIPE_RIGHT',
NO_SWIPE: 'NO_SWIPE',
TOO_SHORT: 'TOO_SHORT'
};
}
}
module.exports = Swiper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment