Home > Web Front-end > JS Tutorial > How Can I Reliably Detect Touchscreen Devices Using JavaScript?

How Can I Reliably Detect Touchscreen Devices Using JavaScript?

Barbara Streisand
Release: 2024-12-10 00:28:10
Original
640 people have browsed it

How Can I Reliably Detect Touchscreen Devices Using JavaScript?

Detecting Touch Screen Devices with JavaScript: An Optimized Approach

For cross-platform compatibility, developers often face the challenge of distinguishing between touch-capable and non-touch devices using JavaScript. This is crucial for customizing user experiences based on device input methods.

Originally, it was suggested that JavaScript could rely on Modernizr's "touchevents" test to ascertain touch screen capabilities. However, this approach is no longer applicable due to the test's removal from Modernizr.

An Updated Detection Method

As of 2021, a reliable and comprehensive way to detect touch-enabled browsers is to check for the following properties:

function isTouchDevice() {
  return (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0));
}
Copy after login
  • 'ontouchstart' in window checks for the presence of the touchstart event listener, which is supported by most touch-capable browsers.
  • navigator.maxTouchPoints > 0 verifies if the browser supports multi-touch gestures.
  • navigator.msMaxTouchPoints > 0 checks for the same functionality in Microsoft's Edge browser.

Further Reading for Advanced Cases

For more complex touch detection scenarios, consider these resources:

  • [You Can't Detect a Touchscreen by Stu Cox](https://www.stuartelliscox.com/blog/you-cant-detect-a-touchscreen/)
  • [Detecting touch: it's the 'why', not the 'how' by Remy Sharp](https://remysharp.com/2013/04/01/detecting-touch/)
  • [Getting touchy presentation by Patrick H. Lauke](https://www.patrickhlauke.com/getting-touchy-with-javascript)

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template