Thursday, August 31, 2017

Javascript touch events

Javascript has the following touch events:
  • touchstart
  • touchmove
  • touchend
  • touchenter
  • touchleave
  • touchcancel
We usually use the following code snippet to detect touch event support

if ('ontouchstart' in window) {
  /* browser with Touch Events
     running on touch-capable device */
}

if (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0)) {
      /* browser with either Touch Events or Pointer Events (from Microsoft, outdated)
         running on touch-capable device */
}

To support both touch-capable device and desktop mouse input, we can listen to both touch event and click event, something like below

blah.addEventListener('touchend', function(e) {
  /* prevent delay and simulated mouse events */
  e.preventDefault();
  someFunction()
});
blah.addEventListener('click', someFunction);

If we need all touch events handling for Mobile web, suggest to check out some open source libraries, like jQuery Mobile, hammerjs, or jQuery-Touch-Events.

No comments:

Post a Comment