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

var $touchArea = $('#touchArea'),
(function (window, document) {
    var Tap = function () {
        
        this.touchStarted = false, // detect if a touch event is sarted
        this.currX = 0,
        this.currY = 0,
        this.cachedX = 0,
        this.cachedY = 0;
        
        //create custom event
        if (typeof CustomEvent === "function") {
            this.event = new CustomEvent('tap', {
                bubbles: true,
                cancelable: true
            });
        } else if (typeof document.createEvent === "function") {
            this.event = document.createEvent('Event');
            this.event.initEvent('tap', true, true);
        } else {
            return false;
        }
    };
}(window,document));
//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');
    }
   
});