Jquery touch swipe event / no jQuery mobile

Stafie Anatolie picture Stafie Anatolie · Sep 14, 2012 · Viewed 9.7k times · Source

I've been looking for a while for a good jQuery library that will allow me to attach touch events to the DOM elements, especially swipe / tap.

I've tried hammer.js, in the documentation it tells that it has swipe effect, but when I try to attach it like $('.element').on('swipe', function(){ //do smth }); it doesn't work.

I was able to simulate the swipe by using its 'dragend' event, but the bad thing is that sometimes it works, sometimes it doesn't.

To be more specific on what I want to achieve - check the twitter website on your phone, and try to swipe left/right a tweet in your timeline/feed, it should reveal some actions buttons for 'Reply' / 'Retweet' / 'Favorite'.

Can anyone give me a code example or a library with good documentation on how I can achieve this?

P.S: I can't use jQuery mobile on this project.

Answer

mddw picture mddw · Sep 14, 2012

I can't help you with a library, but I can copy/paste what I use to make a swipe with JQuery. This exemple is only for a up and down swipe, but quite easy to adapt to other gestures.

This is the plugin part :

;(function($) { 
  $.fn.tactile = function(swipe) {
    return this.each(function() {
      var $this = $(document),
      isTouching = false,
      debut;                                // means start in french

      $this.on('touchstart', debutGeste);       

      function debutGeste() {               // means start of gesture
        if (event.touches.length == 1) {
          debut = event.touches[0].pageY;
          isTouching = true;
          $this.on('touchmove', geste);
        }
      }

      function finGeste() {                 // means end of gesture
        $this.off('touchmove');
        isTouching = false;
        debut = null;
      } 

      function geste() {                   // geste means gesture
        if(isTouching) {
          var actuel = event.touches[0].pageY,
          delta = debut - actuel;

          if (Math.abs(delta) >= 30) {     // this '30' is the length of the swipe
            if (delta > 0) {
              swipe.up();
            } else {
              swipe.down();
            }                       
            finGeste();
          }
        }
        event.preventDefault(); 
      }
    });
  };
})(jQuery);

This is the use part :

$(document).tactile({   
  up: function() { }, 
  down: function() { }
});

I can't promise this is the right way, neither this is good code, but it works.