kotarok
1/17/2016 - 10:13 AM

JavaScript watchSwipe() event observer.

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_);
};