Created
August 5, 2014 02:12
-
-
Save lackneets/f04bad7489384fa4cb7b to your computer and use it in GitHub Desktop.
Detect left/right-swipe on touch-devices, but allow up/down-scrolling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a modification from http://goo.gl/tLbLXr | |
var attachEvent = function(element, event, fn) { | |
if (element.addEventListener) | |
element.addEventListener(event, fn, false); | |
else if (element.attachEvent) // if IE | |
element.attachEvent('on' + event, fn); | |
} | |
var onReady = function(func) { | |
if (document.readyState == 'complete') { | |
func(); | |
} else { | |
attachEvent(window, 'load', func); | |
} | |
} | |
onReady(function(){ | |
(function(d){ | |
var ce=function(e,n){var a=document.createEvent("CustomEvent");a.initCustomEvent(n,true,true,e.target);e.target.dispatchEvent(a);a=null;return false}, | |
nm=true,sp={x:0,y:0},ep={x:0,y:0}, | |
touch={ | |
touchstart:function(e){sp={x:e.touches[0].pageX,y:e.touches[0].pageY}}, | |
touchmove:function(e){nm=false;ep={x:e.touches[0].pageX,y:e.touches[0].pageY}}, | |
touchend:function(e){if(nm){ce(e,'fc')}else{var x=ep.x-sp.x,xr=Math.abs(x),y=ep.y-sp.y,yr=Math.abs(y);if(Math.max(xr,yr)>20){ce(e,(xr>yr?(x<0?'SwipeLeft':'SwipeRight'):(y<0?'SwipeUp':'SwipeDown')))}};nm=true}, | |
touchcancel:function(e){nm=false} | |
}; | |
for(var a in touch){d.addEventListener(a,touch[a],false);} | |
})(document); | |
}); | |
/* Usage: | |
document.body.addEventListener('SwipeLeft', function(){ | |
history.go(-1); | |
}, false); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment