Detecting Touch Swipe Gestures

by kirupa | 25 March 2018

In our web applications, you and I probably haven't done a whole lot of special work to handle touch-based input. Because touch is often treated as a mouse gesture, a lot of things just work for free. With that said, this doesn't mean we can't do a little extra to make our web content a bit more touch optimized. In this tutorial, the little extra is around detecting the direction of a touch swipe that we can then react to. We are going to do all of this using pure 100% grass-fed JavaScript. No 3rd party libraries will be necessary!


This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/detecting_touch_swipe_gestures.htm

This is BRILLIANT! Thank you for breaking this down SO clearly. Just amazing, and just what I needed to add a simple swiper on a custom slideshow. Woot!

1 Like

Glad it worked out :slight_smile:

Uncaught SyntaxError: Malformed arrow function parameter list

Can you post your code? The example on the site still works for me.

Cheers,
Kirupa

Great article, my first intro to touch events; However, I was lost on the explanation of exiting the function when initialX, initialY = null; it was painful to read that part, and I still don’t understand it.
And if the touchMove event keeps firing, does it stop firing when we lift the finger ? The final X,Y co-ords is what is used in the DiffX, DiffY calculations? that part is not clear.

Hi @Lyn_Taylor - welcome to the forums :slight_smile:

Setting initialX and initialY to null at the end is to ensure that any previously stored value isn’t kept around. When you press down on an element with your finger, we set initialX and initialY to the position of the press. This sets us up for moving our finger and detecting the swipe direction which is a “press and move”. If we never pressed down, initialX and initialY would be set to null and the code for dragging will never kick in.

The touchMove event stops firing once you lift the finger. The calculation happens continuously while you are moving your finger around. All we are measuring with diffX and diffY is the position when the finger pressed down and the position now as your finger has moved.

Does this help? I can try to explain differently if needed :slight_smile:

Cheers,
Kirupa