Touch Or Mouse demonstration

Demonstration of our Touch Or Mouse jQuery plugin (https://gist.github.com/lmeurs/e5db12f0b3ef43f9cd65) detects whether an event has been invoked by a touchscreen or a mouse.

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="click">Click me</h1>
<h1 id="touch">Touch me</h1>

CSS

body {
  font: 12px Arial;
}

.link {
  display: inline-block;
  padding: 20px;
  background: #eee;
  text-decoration: none;

  -webkit-transition: background-color 250ms;
  transition: background-color 250ms;
}

.link.hovered {
  color: white;
  background: #555;
}

JavaScript

$('#click').on('mousedown mousemove', function () { alert('Event detected'); });
$('#touch').on('touchend', function () { alert('Event detected'); });
function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
         switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type="mousemove"; break;        
        case "touchend":   type="mouseup"; break;
        default: return;
    }

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                              first.screenX, first.screenY, 
                              first.clientX, first.clientY, false, 
                              false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}