How can I detect device touch support in JavaScript? How can I detect device touch support in JavaScript? google-chrome google-chrome

How can I detect device touch support in JavaScript?


The correct answer is to handle both event types - they're not mutually exclusive.

For a more reliable test for touch support, also look for window.DocumentTouch && document instanceof DocumentTouch which is one of the tests used by Modernizr

Better yet, just use Modernizr yourself and have it do the feature detection for you.

Note though that you cannot prevent false positives, hence my first line above - you've got to support both.


This is a modification of how Modernizr performs touch detection, with added support to work with IE10+ touch devices.

var isTouchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0;

It's not foolproof since detecting a touch device is apparently an impossibility.

Your mileage may vary:

  • Older touchscreen devices only emulate mouse events
  • Some browsers & OS setups may enable touch APIs when no touchscreen is connected, for example, in systems where a driver for a touchscreen is installed, but the touch hardware is not functioning or not installed.
  • In a hybrid mouse/touch/trackpad/pen/keyboard environment, this doesn't indicate which input is being used, only that the browser detects touch hardware present. For example, a user could switch from using a mouse to touching the screen on a touch-enabled laptop or mouse-connected tablet at any moment. It only detects if the browser believes it could accept or emulate a touch input, for example, when using mobile emulation mode in Chrome Dev Tools.

Update:A tip: Do not use touch-capability detection to control & specify UI behaviors, use event listeners instead. Design for the click/touch/keyup event, not the device, touch-capability detection is typically used to save the cpu/memory expense of adding an event listener. One example of where touch detection could be useful and appropriate:

if (isTouchCapable) {    document.addEventListener('touchstart', myTouchFunction, false); }


You should consider using the well tested (and cross-browser) Modernizr's touch test.

From their site:

// bind to mouse events in any caseif (Modernizr.touch){   // bind to touchstart, touchmove, etc and watch `event.streamId`} 

http://modernizr.github.com/Modernizr/touch.html