Detecting the ‘Tap’ event on a Mobile touch device using javascript

tap-event

Currently we can use different types of events to control a touch gesture on a mobile device using javascript, but unfortunately they are not enough to detect all the huge amount of behaviours that an User could do with a touch gesture.
Some of the events that you can catch having everything under control are touchstart, touchmove, touchend and touchcancel.
In one of my projects I needed to detect the ‘Tap’ event that is a bit different from the ‘touchstart’ event *, so I found this solution that works pretty well, and here you can get the code.
*The Tap event should not be confused with the click because they are two things completely different

var $touchArea = $('#touchArea'),
    touchStarted = false, // detect if a touch event is sarted
    currX = 0,
    currY = 0,
    cachedX = 0,
    cachedY = 0;

//setting the events listeners
$touchArea.on('touchstart mousedown',function (e){
    e.preventDefault();
    // caching the current x
    cachedX = e.pageX;
    // caching the current y
    cachedY = e.pageY;
    // a touch event is detected      
    touchStarted = true;
    $touchArea.text('Touchstarted');
    // detecting if after 200ms the finger is still in the same position
    setTimeout(function (){
        currX = e.pageX;
        currY = e.pageY;
        if ((cachedX === currX) && !touchStarted && (cachedY === currY)) {
            // Here you get the Tap event
            $touchArea.text('Tap');
        }
    },200);
});
$touchArea.on('touchend mouseup touchcancel',function (e){
    e.preventDefault();
    // here we can consider finished the touch event
    touchStarted = false;
    $touchArea.text('Touchended');
});
$touchArea.on('touchmove mousemove',function (e){
    e.preventDefault();
    if(touchStarted) {
         // here you are swiping
         $touchArea.text('Swiping');
    }
});

Here it is the result or you can check the demo directly here :

 

3 Comments

  • Rich says:

    An observation, – I see Jquery code and not pure javascript.

    • Yeah you are right, but:

      1. jQuery is Javascript as well (and there is no reason to reinvent the wheel)
      2. The title of the post contains the keyword javascript just to specify that this code works only on a web environment
      3. This example is intentionally not a “vanilla polyfill”, but I am sure that any good frontend developer is able to convert it easily into pure JS (or to make a new one even better)

      I am sorry if this article wasn’t useful for you, but anyway thanks for your feedback :)
      Cheerio

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>