How to Detect a Touch Screen Device Using JavaScript?

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.