It's dead simple to detect Hover and Touch nowadays thanks to Level-4-media-queries.
@media (hover: hover) { //Insert Styles for Hover-Devices }
Detection of non-hover-devices:
@media (hover: none) { //Insert Styles for Non-Hover-Devices }
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. }
You can further specify which device you like to target with pointer:
@media (pointer: fine) { //… } @media (pointer: coarse) { //… }
In JavaScript, the exact same method works thanks to matchMedia:
const canHover = window.matchMedia('(hover: hover)').matches; //true or false
Top comments (2)
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.
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.