Created
September 18, 2014 17:44
-
-
Save codescribblr/8b4af3f0344fd9af1c18 to your computer and use it in GitHub Desktop.
Adds the ability to handle swipe events.
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
| //Example Usage | |
| $('#selector').each(function(){ | |
| swipedetect(this, function (swipedir){ | |
| // swipedir contains either "none", "left", "right", "top", or "down" | |
| if (swipedir =='left') { | |
| $("#selector").parent().find('.next').click(); | |
| } | |
| if (swipedir =='right') { | |
| $("#selector").parent().find('.prev').click(); | |
| } | |
| }); | |
| }); | |
| // From http://www.javascriptkit.com/javatutors/touchevents2.shtml | |
| function swipedetect(el, callback){ | |
| var touchsurface = el, | |
| swipedir, | |
| startX, | |
| startY, | |
| distX, | |
| distY, | |
| threshold = 150, //required min distance traveled to be considered swipe | |
| restraint = 100, // maximum distance allowed at the same time in perpendicular direction | |
| allowedTime = 300, // maximum time allowed to travel that distance | |
| elapsedTime, | |
| startTime, | |
| handleswipe = callback || function (swipedir){} | |
| touchsurface.addEventListener('touchstart', function(e){ | |
| var touchobj = e.changedTouches[0]; | |
| swipedir = 'none'; | |
| dist = 0; | |
| startX = touchobj.pageX; | |
| startY = touchobj.pageY; | |
| startTime = new Date().getTime(); | |
| e.preventDefault(); | |
| }, false); | |
| touchsurface.addEventListener('touchmove', function(e){ | |
| e.preventDefault(); // prevent scrolling when inside DIV | |
| }, false); | |
| touchsurface.addEventListener('touchend', function(e){ | |
| var touchobj = e.changedTouches[0]; | |
| distX = touchobj.pageX - startX; // get horizontal dist traveled by finger while in contact with surface | |
| distY = touchobj.pageY - startY; // get vertical dist traveled by finger while in contact with surface | |
| elapsedTime = new Date().getTime() - startTime; | |
| if (elapsedTime <= allowedTime) { | |
| if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) { | |
| swipedir = (distX < 0)? 'left' : 'right'; | |
| } | |
| else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ | |
| swipedir = (distY < 0)? 'up' : 'down' | |
| } | |
| } | |
| handleswipe(swipedir); | |
| e.preventDefault(); | |
| }, false) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment