Detecting Hover and Touch in CSS and JS
Antonio Radovcic

Antonio Radovcic @niorad

About: Front-End-Developer, DevLids.com

Location:
Munich
Joined:
Jan 10, 2017

Detecting Hover and Touch in CSS and JS

Publish Date: Oct 2 '19
8 2

It's dead simple to detect Hover and Touch nowadays thanks to Level-4-media-queries.

@media (hover: hover) {
  //Insert Styles for Hover-Devices
}
Enter fullscreen mode Exit fullscreen mode

Detection of non-hover-devices:

@media (hover: none) {
  //Insert Styles for Non-Hover-Devices
}
Enter fullscreen mode Exit fullscreen mode

For IE11-support, extend the media-query with a IE11-hack:

@media (hover: hover), screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  //Insert Styles for Hover-Devices and IE11 here.
}
Enter fullscreen mode Exit fullscreen mode

You can further specify which device you like to target with pointer:

@media (pointer: fine) {
  //
}
@media (pointer: coarse) {
  //
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript, the exact same method works thanks to matchMedia:

const canHover = window.matchMedia('(hover: hover)').matches; //true or false
Enter fullscreen mode Exit fullscreen mode

Comments 2 total

  • David-Carty
    David-CartyFeb 28, 2020

    Far from perfect. My mobile phone (Galaxy S8+ ) has a mouse according to the code directly above. Yes, I was surprised but the fact remains.

    • Antonio Radovcic
      Antonio RadovcicFeb 28, 2020

      I could check that and try to add this case, which Android-Version and which Browser is used?

      Of course there will always be edge-cases with e.g. stylus-based devices or touch/mouse-hybrids. That's why websites shouldn't rely on hover to begin with.

Add comment