Skip to content

Instantly share code, notes, and snippets.

@anutron
Created March 27, 2013 18:56
Show Gist options
  • Select an option

  • Save anutron/5257017 to your computer and use it in GitHub Desktop.

Select an option

Save anutron/5257017 to your computer and use it in GitHub Desktop.
['touchstart', 'touchmove', 'touchend'].each(function(type){
Element.NativeEvents[type] = 2;
});
Element.Events.swipe = {
onAdd: function(fn){
var startX, startY, active = false;
var touchStart = function(event){
active = true;
startX = event.event.touches[0].pageX;
startY = event.event.touches[0].pageY;
};
var touchMove = function(event){
var endX = event.event.touches[0].pageX,
endY = event.event.touches[0].pageY,
diffX = endX - startX,
diffY = endY - startY,
isLeftSwipe = diffX < -1 * Element.Events.swipe.swipeWidth,
isRightSwipe = diffX > Element.Events.swipe.swipeWidth;
if (active && (isRightSwipe || isLeftSwipe)
&& (event.onlySwipeLeft ? isLeftSwipe : true)
&& (event.onlySwipeRight ? isRightSwipe : true) ){
active = false;
fn.call(this, {
'direction' : isRightSwipe ? 'right' : 'left',
'startX' : startX,
'endX' : endX
});
} else if (Element.Events.swipe.cancelVertical
&& Math.abs(startY - endY) < Math.abs(startX - endX)){
return false;
} else {
var isUpSwipe = diffY < -1 * Element.Events.swipe.swipeHeight,
isDownSwipe = diffY > Element.Events.swipe.swipeHeight;
if (active && (isUpSwipe || isDownSwipe)
&& (event.onlySwipeDown ? isDownSwipe : true)
&& (event.onlySwipeUp ? isUpSwipe : true) ){
active = false;
fn.call(this, {
'direction' : isUpSwipe ? 'up' : 'down',
'startY' : startY,
'endY' : endY
});
}
}
}
this.addEvent('touchstart', touchStart);
this.addEvent('touchmove', touchMove);
var swipeAddedEvents = {};
swipeAddedEvents[fn] = {
'touchstart' : touchStart,
'touchmove' : touchMove
};
this.store('swipeAddedEvents', swipeAddedEvents);
},
onRemove: function(fn){
$H(this.retrieve('swipeAddedEvents')[fn]).each(function(v,k){
this.removeEvent(k,v);
}, this);
}
};
Element.Events.swipe.swipeWidth = 70;
Element.Events.swipe.swipeHeight = 70;
Element.Events.swipe.cancelVertical = true;
@NKjoep
Copy link
Copy Markdown

NKjoep commented Mar 28, 2013

Good stuff Aaron!

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