Home >Web Front-end >JS Tutorial >How Can JavaScript Reliably Detect Touch Screen Devices?

How Can JavaScript Reliably Detect Touch Screen Devices?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 16:08:18985browse

How Can JavaScript Reliably Detect Touch Screen Devices?

Distinguishing Touch Screen Devices with JavaScript

Problem:

Incorporating touch screen functionality into both desktop and mobile applications requires JavaScript detection of touch screen capabilities. However, how can this be achieved in a reliable manner?

Answer:

Evaluating Modernizr's Approach:

Initially, the widely respected Modernizr library was a viable option for detecting touch screens. However, it has since removed its "touchevents" tests due to their ambiguity.

Current Recommendations:

Determining Touch Capabilities:

As of 2021, the following code snippet offers a practical approach to detecting touch capabilities:

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

Assessing Subtleties:

It's important to acknowledge that detecting touch screens can be nuanced. For more advanced scenarios, consider exploring resources such as:

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

The above is the detailed content of How Can JavaScript Reliably Detect Touch Screen Devices?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn