DEV Community

tux0r
tux0r

Posted on

(Safely) Detect touch support with JavaScript

I just needed to solve this very problem and I thought that some of you might need it later:

As user agent strings are both unreliable and about to be phased out, we need better ways to detect if the user has a touch-enabled device. Luckily, we have CSS4 media queries:

const deviceHasAMouse = window.matchMedia("(any-hover: hover)").matches;
Enter fullscreen mode Exit fullscreen mode

See also MDN.

Enjoy.

Discussion (1)

Collapse
nabbisen profile image
Heddi Nabbisen

CSS4. It sounds exciting to me 🙂