Created
November 17, 2011 16:00
-
-
Save localpcguy/1373518 to your computer and use it in GitHub Desktop.
Simple Mobile Swipe function to get the swipe direction
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
var swipeFunc = { | |
touches : { | |
"touchstart": {"x":-1, "y":-1}, | |
"touchmove" : {"x":-1, "y":-1}, | |
"touchend" : false, | |
"direction" : "undetermined" | |
}, | |
touchHandler: function(event) { | |
var touch; | |
if (typeof event !== 'undefined'){ | |
event.preventDefault(); | |
if (typeof event.touches !== 'undefined') { | |
touch = event.touches[0]; | |
switch (event.type) { | |
case 'touchstart': | |
case 'touchmove': | |
swipeFunc.touches[event.type].x = touch.pageX; | |
swipeFunc.touches[event.type].y = touch.pageY; | |
break; | |
case 'touchend': | |
touches[event.type] = true; | |
if (swipeFunc.touches.touchstart.x > -1 && swipeFunc.touches.touchmove.x > -1) { | |
swipeFunc.touches.direction = swipeFunc.touches.touchstart.x < swipeFunc.touches.touchmove.x ? "right" : "left"; | |
// DO STUFF HERE | |
alert(touches.direction); | |
} | |
default: | |
break; | |
} | |
} | |
} | |
}, | |
init: function() { | |
document.addEventListener('touchstart', swipeFunc.touchHandler, false); | |
document.addEventListener('touchmove', swipeFunc.touchHandler, false); | |
document.addEventListener('touchend', swipeFunc.touchHandler, false); | |
} | |
}; | |
swipeFunc.init(); |
Throws error on iPad iOS 9.2 on line 21!
ReferenceError: Can't find variable: touches
You should use "swipeFunc.touches" rather than "touches" in lines 21 and 26. Also I had to comment out line 11 (event.preventDefault()) to avoid disabling browser scrolling.
This is perfect.
But on some of the andorid devices doesn't able to get the touchend event when we not using the event.preventDefault(). Can you please help ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1