Skip to content

Instantly share code, notes, and snippets.

@influxweb
Last active October 15, 2020 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save influxweb/2b462e25f97e11199599619fa079fb5d to your computer and use it in GitHub Desktop.
Save influxweb/2b462e25f97e11199599619fa079fb5d to your computer and use it in GitHub Desktop.
How to detect touch device in modern browsers

https://stackoverflow.com/a/63666289/1084300

This is really simple with just one line of code:

const touch = matchMedia('(hover: none)').matches;

  • What? matchMedia?
  • This is just a JS API to do CSS @media queries. And it is supported in modern browsers: https://caniuse.com/#feat=matchmedia. Of course, you may use such queries directly in CSS:
@media (hover: none){
    /* touch stuff goes here */
}
  • Ok, what @media queries may be also useful?
@media (hover: none) and (pointer: coarse) {
    /* touchscreens */
}
@media (hover: none) and (pointer: fine) {
    /* stylus */
}
@media (hover: hover) and (pointer: coarse) {
    /* controllers */
}
@media (hover: hover) and (pointer: fine) {
    /* mouse or touchpad */
}

However, this will query only the primary input method. If you want to go deeper, you may use any-hover and any-pointer to query all input devices.

For better coverage, it would be preferable to use:

const touch = matchMedia('(hover: none), (pointer: coarse)').matches;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment