DEV Community


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.


Discussion (1)

nabbisen profile image
Heddi Nabbisen

CSS4. It sounds exciting to me 🙂