public
Last active

Handle Touch and Mouse Events

  • Download Gist
touch-mouse.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Keep a reference available throughout the code
var touch = null;
 
// Called when the document has loaded
// You may choose some other place to do this
// Needs to occur only once
function doLoad()
{
var element = null;
 
// Check to see if there is a touch event handler
touch = ( 'ontouchstart' in document.documentElement ) ? true : false;
 
// Get your desired element to handle the interaction event
// Quick ternary operation based on previous findings
element = document.querySelector( '#yourElement' );
element.addEventListener( touch ? 'touchstart' : 'mousedown', doInputStart );
}
 
// Called when the mouse is down or the touch has started
// Does whatever you want on that event
function doInputStart( evt )
{
var clientX = null;
var clientY = null;
 
// Get the coordinates based on input type
if( touch )
{
// Stop the default handling of the event
evt.preventDefault();
// Get the touch coordinates
clientX = evt.touches[0].clientX;
clientY = evt.touches[0].clientY;
} else {
// Not a tablet so grab mouse coordinates
clientX = evt.clientX;
clientY = evt.clientY;
}
 
// Do whatever you want at this point
console.log( 'Input at: ' + clientX + 'x' + clientY );
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.