Sometimes, we may need to detect a touch screen device with JavaScript.
In this article, we’ll look at how to detect a touch screen device with JavaScript.
Checking for the ontouchstart Method and maxTouchPoints
One way to check for a touch screen device is to check for the window.ontouchstart
method and the navigator.maxTouchPoints
property.
For instance, we can write:
const isTouchDevice = () => {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
console.log(isTouchDevice())
We check all the items present for a touchscreen device with:
('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0)
ontouchstart
lets us assign a touch event listener to it that runs when we start touching the screen.
maxTouchPoints
returns the number of touchpoints of the screen.
And navigator.msMaxTouchPoints
is the Microsoft version of the maxTouchPoints
property.
This is a cross-browser solution that works on most modern browsers.
The window.matchMedia Test
Also, we can use the window.matchMedia
method to test whether a device has any touchscreen features present.
For instance, we can write:
const isTouchDevice = () => {
return window.matchMedia("(pointer: coarse)").matches
}
console.log(isTouchDevice())
We test whether the pointer: coarse
CSS feature is present.
And if it is, we know the device the app is running on is a touch screen device.
Conclusion
We can test for various touch features of a device with JavaScript to check whether a device is a touch device in our JavaScript web app.
3 replies on “How to Detect a Touch Screen Device Using JavaScript?”
Shouldn’t that ‘matchMedia’ test be checking for the not condition. If there is a pointing device (coarse or fine) then it’s not a touch-enabled device.
pointer: course are available on devices with a pointing device with limited accuracy, which includes touch screens.
'ontouchstart' in window
is not reliable. For example, my desktop has no touchscreen, yet: https://i.imgur.com/emVPVFz.png