Skip to content

Instantly share code, notes, and snippets.

@localpcguy
Created November 17, 2011 16:00
Show Gist options
  • Save localpcguy/1373518 to your computer and use it in GitHub Desktop.
Save localpcguy/1373518 to your computer and use it in GitHub Desktop.
Simple Mobile Swipe function to get the swipe direction
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();
@abrjagad
Copy link

abrjagad commented Apr 2, 2014

Excellent.

@kowach
Copy link

kowach commented Aug 21, 2014

This is perfect.

@sp90
Copy link

sp90 commented Oct 27, 2014

Simply perfect - love the simplicity

@RohitLuthra19
Copy link

how to use it

@jazekmon
Copy link

jazekmon commented Jul 7, 2015

You can make it OOP. Below is an example, adjusted to only catch left and right swipes (did some adjustments on the swipe detection by adding a swipe's minimum length):

var swipeFunc = function() {
  this._swipe_direction = ['left','right'];
  this._y_diff = -1;
  this._x_diff = -1;
  this._x_min_length = 30;
  this.touches = {
    'touchstart': {'entered':false,'x':-1, 'y':-1},
    'touchmove' : {'entered':false,'x':-1, 'y':-1},
    'touchend'  : false,
    'direction' : 'undetermined'
  };
};
swipeFunc.prototype = {
  touchHandler: function(event) {
    var event_handle = this.handle, touch;
    if(typeof event !== 'undefined'){
      event.preventDefault();
      if(event.touches !== 'undefined'){
        touch = event.touches[0];
        switch (event.type) {
          case 'touchstart':
          case 'touchmove':
            event_handle.touches[event.type].entered = true;
            event_handle.touches[event.type].x = touch.pageX;
            event_handle.touches[event.type].y = touch.pageY;
            break;
          case 'touchend':
            event_handle.touches[event.type] = true;
            if(!event_handle.touches.touchmove.entered)
              break;
            event_handle._y_diff = event_handle.touches.touchstart.y > event_handle.touches.touchmove.y ? event_handle.touches.touchstart.y - event_handle.touches.touchmove.y : event_handle.touches.touchmove.y - event_handle.touches.touchstart.y;
            event_handle._x_diff = event_handle.touches.touchstart.x > event_handle.touches.touchmove.x ? event_handle.touches.touchstart.x - event_handle.touches.touchmove.x : event_handle.touches.touchmove.x - event_handle.touches.touchstart.x;
            if (event_handle.touches.touchstart.x > -1 && event_handle.touches.touchmove.x > -1 && event_handle._x_diff > event_handle._x_length_sensitivity && event_handle._x_diff >= event_handle._y_diff) {
              event_handle.touches.direction = event_handle.touches.touchstart.x < event_handle.touches.touchmove.x ? 'right' : 'left';

              // DO STUFF HERE
              //alert(event_handle.touches.direction);

              // checking the swipe direction example:
              for(var k in event_handle._swipe_direction){
                if(event_handle.touches.direction == event_handle._swipe_direction[k])
                  alert(event_handle.touches.direction);
              }
            }
          default:
            break;
        }
      }
    }
  },
  init: function(opts) {
    this._swipe_direction = opts.swipe_dir !== undefined ? opts.swipe_dir : this._swipe_direction;
    this._x_min_length = opts.x_min_length !== undefined ? opts.x_min_length : this._x_min_length;
    document.getElementsByClassName(opts.main_target)[0].addEventListener('touchstart', this.touchHandler, false); 
    document.getElementsByClassName(opts.main_target)[0].addEventListener('touchmove', this.touchHandler, false); 
    document.getElementsByClassName(opts.main_target)[0].addEventListener('touchend', this.touchHandler, false); 
    document.getElementsByClassName(opts.main_target)[0].handle = this;
  }
};
var swipeFunc_1 = new swipeFunc(), swipeFunc_2 = new swipeFunc();
// default left/right swipe detection
swipeFunc_1.init({
  main_target:'class_name_of_target1'
});
// catch only left swiping, with adjustable minimum swipe length
swipeFunc_2.init({
  main_target:'class_name_of_target2',
  swipe_dir: ['left'],
  x_min_length: 40
});

@brandondurham
Copy link

brandondurham commented Apr 21, 2016

Moved this into a React component and converted the touches object to state. Thought I’d share: https://gist.github.com/brandondurham/e5a0cb09b280076ca74e5a06e59d5ad4

Thanks for the inspiration!

@joerhoney
Copy link

Do you have any kind of demo site for this, or can you provide a JSFiddle or CodePen example or something? Javascript is not a second language some of us, but we can usually figure out how to use something like this if we have some examples to go by. Looks like a great script (especially with how lightweight it is), but I don't know how to integrate it into what I'm doing (which in my case is already an object, but that's another bag of tricks). A working demo would really help with integration. I know you don't have to provide that and I hope I'm not requesting too much, but that would really help show the value of this script, which to me looks like a potential winner.

@mikepaszkiewicz
Copy link

+1

@smohadjer
Copy link

smohadjer commented Jun 8, 2016

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.

@centhi
Copy link

centhi commented Jul 1, 2016

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