JSFiddle - React, Tailwind, and code Playground

by gianlucaguarini

HTML

<div id="touchArea"></div>

CSS

#touchArea {
    width:400px;
    height:400px;
    background:#333;
    font-size:20px;
    color:#fff;
}

JavaScript

// helpers
var $ = document.querySelector.bind(document),
    $$ = document.querySelectorAll.bind(document),
    setListener = function (elm,events,callback) {
        var eventsArray = events.split(' '),
            i = eventsArray.length;
        while(i--){
            elm.addEventListener( eventsArray[i], callback, false );
        }
    };

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

//setting the events listeners
setListener($touchArea,'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.innerHTML = '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.innerHTML = 'Tap';
        }
    },200);
});
setListener($touchArea,'touchend mouseup touchcancel',function (e){
    e.preventDefault();
    // here we can consider finished the touch event
    touchStarted = false;
    $touchArea.innerHTML = 'Touchended';
});
setListener($touchArea,'touchmove mousemove',function (e){
    e.preventDefault();
    if(touchStarted) {
         // here you are swiping
         $touchArea.innerHTML = 'Swiping';
    }
   
});