Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if Hover Exists or Is Available

Everyone has been pushing towards feature detection for a long time. I'd like to detect if a visitor's browser supports the :hover pseudo class. It's my understanding there are enough, if not most, mobile devices that do not support hovering, so I'd like to gear my event listeners accordingly. But without mobile detection, I'm unsure how to accomplish this, and I've not found anything via Google or SO thus far.

Perhaps something similar to question #8981463

$(function() {
  var canHover = $(document).is(":hover");
});

I won't be able to test this on a mobile device 'till next week.

Thoughts?

like image 332
Keith DC Avatar asked May 09 '14 05:05

Keith DC


Video Answer


2 Answers

There is no is(':hover'), you can't detect CSS pseudo classes with javascript as they are not part of the DOM.

You can however detect certain events that are only available on touch screens and act accordingly, modernizer does something like this

if ('ontouchstart' in document.documentElement) {
  document.documentElement.classList.add('touch');
} else {
  document.documentElement.classList.add('no-touch');
}

where it adds classes to the <html> element that tells you wether or not the device has a touch screen or not, so you can do something like this in CSS

.no-touch .element:hover {color: red;} // for users with a mouse
.touch .element {color: blue;} // for touch devices
like image 140
adeneo Avatar answered Sep 18 '22 01:09

adeneo


There is now a well-supported media query to detect whether hover is supported: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/hover

Which you can use with Window.matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

Then you would use:

if (window.matchMedia( "(hover: none)" ).matches) {
   // hover unavailable
}
like image 26
mandelf Avatar answered Sep 22 '22 01:09

mandelf