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?
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With