Support Swipe on mobile devices
wordpress, code, magento, webdev
January 7th 2015 (5 years ago)
I was working for a client, who has a very strict policy about using open source javascript libraries – they simply don’t do it, which in some cases – I totally agree.
Now, everyone wants to be super extra trendy programmer, so they need to build up they own libs/frameworks etc. and don’t get me wrong – if you have time/energy and nothing better to do, go for it.
But, if you just need a good, simple and a quick solution, there are is at least one and i found the one, that in this scenario was the best.

Touch events

Nothing to explain here actually, Mozilla did for me, and they did it very good, just go there and read about touch Events and how to handle them. We will use two touch events: touchstart and touchmove

The Code

The only library, that the whole engine of my client website is based on isjQuery 1.11.1, which is more than enough for that.
The purpose was to add a swipe functionality to a gallery, which will open when you click on a thumbnail.
I assume you already know how to detect mobile devices(either through Javascript or any other way), if not, write a comment – I can describe some most popular ways to detect mobile devices and distinct rendering of content between the devices.

Hooking to event

  var mobileLastTouchPositionX;
  
  $(document).on('touchstart', function (e)
  {
    mobileLastTouchPositionX = e.originalEvent.touches[0].clientX;
  });
  $(document).on('touchmove', function (e)
  {
    e.preventDefault();
    var touchTime = new Date().getTime(),
        touchLag = 400,
        mobileTouchPositionX = e.originalEvent.touches[0].clientX;

    if(mobileTouchPositionX > mobileLastTouchPositionX &amp;&amp; (mobileLastTouchtime + touchLag) < touchTime)
    {
      $.fancybox.prev();
    }
    else if(mobileTouchPositionX < mobileLastTouchPositionX &amp;&amp; (mobileLastTouchtime + touchLag) < touchTime)
    {
      $.fancybox.next();
    }
    mobileLastTouchPositionX = mobileTouchPositionX;
    mobileLastTouchtime = touchTime;
  });

Releasing the event

This occurs, when user decides to close the gallery(preferably,releasing should be before the animation of closing the gallery ends).
  $(document).off('touchstart');
  $(document).off('touchmove');
The solution was checked (and worked) on:
  • Samsung S3 (Android 4.0.4)
  • Samsung S4 (Android 4.2.2)
  • Samsung S5 (Android 4.4.2)
  • Samsung S5 (Android 4.4.2)
  • Samsung S5 (Android 4.4.4)
  • Ipad Mini 2 (IOS)
  • Iphone 5 (IOS)
  • Iphone 6 (IOS)
  • XPS 10 Tablet(Windows 8.1)