Skip to content

Instantly share code, notes, and snippets.

@naeluh
Last active August 29, 2015 14:07
Show Gist options
  • Save naeluh/1747fcb7325beaadb6a3 to your computer and use it in GitHub Desktop.
Save naeluh/1747fcb7325beaadb6a3 to your computer and use it in GitHub Desktop.
// 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 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment