What’s the best way to detect a ‘touch screen’ device using JavaScript?

UPDATE 2021

To see the old answers: check the history. I decided to start on a clean slate as it was getting out of hands when keeping the history in the post.

My original answer said that it could be a good idea to use the same function as Modernizr was using, but that is not valid anymore as they removed the “touchevents” tests on this PR: https://github.com/Modernizr/Modernizr/pull/2432 due to it being a confusing subject.

With that said this should be a fairly ok way of detecting if the browser has “touch capabilities”:

function isTouchDevice() {
  return (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0));
}

But for more advanced use cases far more smarter persons than me have written about this subject, I would recommend reading those articles:

  • Stu Cox: You Can’t Detect a Touchscreen
  • Detecting touch: it’s the ‘why’, not the ‘how’
  • Getting touchy presentation by Patrick H. Lauke

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)