Skip to content

Instantly share code, notes, and snippets.

@YannickGagnon
Created July 22, 2013 17:49
Show Gist options
  • Save YannickGagnon/6055968 to your computer and use it in GitHub Desktop.
Save YannickGagnon/6055968 to your computer and use it in GitHub Desktop.
Mootools Custom Events - Swipe
/*
---
name: Swipe
description: Provides a custom swipe event for touch devices
authors: Christopher Beloch (@C_BHole), Christoph Pojer (@cpojer), Ian Collins (@3n)
license: MIT-style license.
requires: [Core/Element.Event, Custom-Event/Element.defineCustomEvent, Browser.Features.Touch]
provides: Swipe
...
*/
(function(){
var name = 'swipe',
distanceKey = name + ':distance',
cancelKey = name + ':cancelVertical',
dflt = 50;
var start = {}, disabled, active;
var clean = function(){
active = false;
};
var events = {
touchstart: function(event){
if (event.touches.length > 1) return;
var touch = event.touches[0];
active = true;
start = {x: touch.pageX, y: touch.pageY};
},
touchmove: function(event){
if (disabled || !active) return;
var touch = event.changedTouches[0],
end = {x: touch.pageX, y: touch.pageY};
if (this.retrieve(cancelKey) && Math.abs(start.y - end.y) > 10){
active = false;
return;
}
var distance = this.retrieve(distanceKey, dflt),
deltaX = end.x - start.x,
deltaY = end.y - start.y,
isLeftSwipe = deltaX < -distance,
isRightSwipe = deltaX > distance;
// if swiping in diagonal, cancel swipe
if( (isLeftSwipe || isRightSwipe) && Math.abs(deltaY) > Math.abs(deltaX)) {
return;
}
if (!isRightSwipe && !isLeftSwipe)
return;
event.preventDefault();
active = false;
event.direction = (isLeftSwipe ? 'left' : 'right');
event.start = start;
event.end = end;
this.fireEvent(name, event);
},
touchend: clean,
touchcancel: clean
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment