Detecting Swipe Using jQuery

I’ve run into a situation where I needed to detect if the user swiped on the page and I didn’t want to include a 3rd party jQuery plug-in. By just using the jQuery library, you can detect when a user swipes the page and do whatever you need accordingly. This swipe triggers in any direction. If you want to detect horizontal or vertical only, you’ll have to change the code around a little.

$(function() {
  $("#surface")
    .on('mousedown touchstart', function (e) {
      console.log("(x,y) = (" + e.pageX + "," + e.pageY +")");
      xDown = e.pageX;
      yDown = e.pageY;
    })
    .on('mouseup touchend',function (e) {
      console.log("(x,y) = (" + e.pageX + "," + e.pageY +")");
      xUp = e.pageX;
      yUp = e.pageY;
      if (xDown != xUp || yDown != yUp) {
        alert('Swiped');
      }
    })
  ;
})(jQuery);

You can see this code on CoderWall and Forrst.

Leave a Reply

Your email address will not be published. Required fields are marked *