DEV Community

Antonio Radovcic
Antonio Radovcic

Posted on

Detecting Hover and Touch in CSS and JS

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

Top comments (2)

Collapse
 
davidcarty profile image
David-Carty

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.

Collapse
 
niorad profile image
Antonio Radovcic

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.