Home >Web Front-end >JS Tutorial >How Can JavaScript Reliably Detect Touch Screen Devices?
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:
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!