ericek111

SwipeDetect "library"

Aug 20th, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function swipedetect(el, callback){
  2.  
  3.     var touchsurface = el,
  4.     swipedir,
  5.     startX,
  6.     startY,
  7.     distX,
  8.     distY,
  9.     threshold = 100, //required min distance traveled to be considered swipe
  10.     restraint = 170, // maximum distance allowed at the same time in perpendicular direction
  11.     allowedTime = 400, // maximum time allowed to travel that distance
  12.     touchTime = 300,
  13.     touchDist = 30,
  14.     elapsedTime,
  15.     startTime,
  16.     handleswipe = callback || function(swipedir){}
  17.  
  18.     touchsurface.addEventListener('touchstart', function(e){
  19.         var touchobj = e.changedTouches[0]
  20.         swipedir = 'none'
  21.         dist = 0
  22.         startX = touchobj.pageX
  23.         startY = touchobj.pageY
  24.         startTime = new Date().getTime() // record time when finger first makes contact with surface
  25.     }, false)
  26.  
  27.     touchsurface.addEventListener('touchend', function(e){
  28.         var touchobj = e.changedTouches[0]
  29.         distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
  30.         distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
  31.         elapsedTime = new Date().getTime() - startTime // get time elapsed
  32.         if (elapsedTime <= allowedTime){ // first condition for awipe met
  33.             if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
  34.                 swipedir = (distX < 0)? 'left' : 'right'
  35.                 e.preventDefault();
  36.                 handleswipe(swipedir, touchobj.pageX, touchobj.pageY);
  37.             } else if(elapsedTime <= touchTime) {
  38.                 if(Math.abs(distX) <= touchDist && Math.abs(distY) <= touchDist) swipedir = 'touch';
  39.                 handleswipe(swipedir, touchobj.pageX, touchobj.pageY);
  40.             }
  41.         }
  42.     }, false)
  43. }
Advertisement
Add Comment
Please, Sign In to add comment