Overview

In this guide, you will learn how to capture touch events from mobile devices like swipe left, right, up and Down

Snippet

Create a file called touch.js and copy & paste the following code snippet:


const Touch = {
    state: {
      xDown:null,
      yDown:null
    },
    getTouches: (evt) => {
      return evt.touches ||             // browser API
             evt.originalEvent.touches; // jQuery
    },

    handleTouchStart: (evt) => {
        let firstTouch = Touch.getTouches(evt)[0];
        Touch.state.xDown = firstTouch.clientX;
        Touch.state.yDown = firstTouch.clientY;
    },

    handleTouchMove: (evt) => {
        let action = null;
        let {xDown,yDown} = Touch.state;
        if ( ! xDown || ! yDown ) {
            return;
        }

        let xUp = evt.touches[0].clientX;
        let yUp = evt.touches[0].clientY;

        let xDiff = xDown - xUp;
        let yDiff = yDown - yUp;

        if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
            if ( xDiff > 0 ) {
                /* left swipe */
                action =  'left';
            } else {
                /* right swipe */
                action = 'right';
            }
        } else {
            if ( yDiff > 0 ) {
                /* up swipe */
                action = 'up';
            } else {
                /* down swipe */
                action = 'down';
            }
        }
        /* reset values */
        Touch.state.xDown = null;
        Touch.state.yDown = null;
        return action;
    }
}

export default Touch;

Now link this file in your html template using script tag.

<script type="text/javascript" src="./touch.js" type="text/javascript"></script>

Usage

document.addEventListener('touchstart', Touch.handleTouchStart, false);        
document.addEventListener('touchmove', Touch.handleTouchMove, false);

If you are using React, you can capture events like this:

                        <img
                            onTouchStart={(e)=>Touch.handleTouchStart(e)}
                            onTouchMove={(e)=>{
                                let action = Touch.handleTouchMove(e);
                                if(action == 'left'){
                                    {* Do something here *}
                                }
                                if(action == 'right'){
                                    {* Do something here *}
                                }
                            }}
                        />