Determine touch support and add handlers.

Determine if touch events are available and use a single line to add an event listener to handle mouse or touch in most cases.

touch = ( 'ontouchstart' in document.documentElement ) ? true : false;

// Quick ternary operation based on previous findings
element = document.querySelector( '#yourElement' );
element.addEventListener( touch ? 'touchstart' : 'mousedown', doInputStart );

// 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 touch so grab mouse coordinates
  clientX = evt.clientX;
  clientY = evt.clientY;
}
Published: 6/20/2013
Author: Kevin Hoyt
Tags: touch mobile event
comments powered by Disqus