Detect if the device is touch enabled using JavaScript?

Answered
coderguy asked this question 5 months ago
coderguy on Mar 8

In my web application, I need to detect whether or not the device is touch enabled. If it is a touch enabled device, I need to call different code.

if (isTouchScreenDevice) {
  // do something
}

How can I detect this in my JavaScript code?

3 suggested answers
moon_man41 on Mar 27 · Edited

This should help you detect a touch enabled device:

if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)) {
  // is a touch screen
} else {
  // is not a touch screen
}
0 replies
rusty1_rusty1 on Mar 27

You can use a combination of checking if the "ontouchstart event exists and if the device contains maxTouchPoints:

function isTouchEnabled() {
  return 
    ("ontouchstart" in window) ||
    (navigator.maxTouchPoints > 0) ||
    (navigator.msMaxTouchPoints > 0)
}
0 replies
itsbambi on Mar 27
function detectTouchDevice() {
  var result = false;
  if (window.PointerEvent && ("maxTouchPoints" in navigator)) {
    if (navigator.maxTouchPoints > 0) {
      result = true;
    }
  } else {
    if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
      result = true;
    } else if (window.TouchEvent || ("ontouchstart" in window)) {
      result = true;
    }
  }

  return result;
}
  1. If pointer events are supported, it just checks navigator.maxTouchPoints.
  2. If pointer events aren't supported, it checks the any-pointer:coarse media feature, which uses window.matchMedia.
  3. Checks for window.TouchEvent as a last resort.

There may be scenarios where you detect a touch device. But that doesn't mean a user is actually using the touch screen functionality of the device. For example, if a laptop computer has a touch screen but the user is using the keyboard and/or mouse.

0 replies
Answered