Skip to content

Instantly share code, notes, and snippets.

@kotarok
Last active January 18, 2016 03:17
Show Gist options
  • Save kotarok/36eeb16115f79268fdc3 to your computer and use it in GitHub Desktop.
Save kotarok/36eeb16115f79268fdc3 to your computer and use it in GitHub Desktop.
JavaScript watchSwipe() event observer.
var watchSwipe = function(el) {
var d = {};
var SWIPWE = 'swipe',
FLICK = 'flick',
DIRECTIONS = ['Up', 'Left', 'Right', 'Down'],
SWIPE_MIN_MOVE = 50,
FLICK_MIN_MOVE = 30,
FLICK_MIN_VELO = 1;
el.touchstartListener_ = function(e) {
d.duration = Date.now();
d.distance = 0;
d.startX = e.touches[0].pageX;
d.startY = e.touches[0].pageY;
};
el.touchendListener_ = function(e) {
// set end coordination if it moves further than minimum length
d.endX = e.changedTouches[0].pageX;
d.endY = e.changedTouches[0].pageY;
var moveX = Math.abs(d.endX - d.startX);
var moveY = Math.abs(d.endY - d.startY);
d.distance = Math.sqrt(moveX * moveX + moveY * moveY);
if (Math.abs(d.distance) < SWIPE_MIN_MOVE) {
return false;
}
// Calc velocity
d.duration = Date.now() - d.duration;
d.velocity = d.distance / d.duration;
// detect move direction from relative coordination
var direction = DIRECTIONS[parseInt(
((moveY > -moveX) - 0 + '') +
((moveY > moveX) - 0),
2)];
var verboseSwipeEventName = SWIPWE + direction;
var verboseFlickEventName = FLICK + direction;
d.direction = direction.toLowerCase();
if (d.velocity > FLICK_MIN_VELO) {
d.type = FLICK;
el.dispatchEvent(new CustomEvent(FLICK, {detail: d}));
el.dispatchEvent(new CustomEvent(verboseFlickEventName, {detail: d}));
} else {
d.type = SWIPWE;
}
el.dispatchEvent(new CustomEvent(SWIPWE, {detail: d}));
el.dispatchEvent(new CustomEvent(verboseSwipeEventName, {detail: d}));
};
el.addEventListener('touchstart', el.touchstartListener_);
el.addEventListener('touchend', el.touchendListener_);
};
var unwatchSwipe = function() {
el.removeEventListener('touchstart', el.touchstartListner_);
el.removeEventListener('touchend', el.touchendListener_);
};
@kotarok
Copy link
Author

kotarok commented Jan 17, 2016

You can watch swipe or flick event easily via general .addEventListener API.

watchSwipe(element);
element.addEventListener('swipe', fn);

Watch swipe or flick motion on given element. If it's detected, fire custom event, like:

  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown
  • flick, flickLeft, flickRight, flickUp, flickDown

Those events are fired by velocity and direction of touch movement. If it moves fast enough, flick event would be fired as well as swipe event.

event object has detail property which has more detail information, like: coordinations, direction, distance, duration or velocity. You can use them if needed.

Also you can do unwatchSwipe(el).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment