Is there a way to remove or prevent all hover effects on a touch device? I've tried various scripts, but none seem to work for me. How can I test it with dev tools? I attempted this script but received an error: Cannot read property 'addEventListener' of null. Interestingly, it works here codepen. Could the error be because the dom tree has not loaded yet?
<html class="hover-active">
$(window).on('load', function() {
if (!('addEventListener' in window)) {
return;
}
var htmlElement = document.querySelector('html');
function touchStart() {
htmlElement.classList.remove('hover-active');
htmlElement.removeEventListener('touchstart', touchStart);
}
htmlElement.addEventListener('touchstart', touchStart);
});
I also tried this method:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){}
In addition, I experimented with using modernizr, which only seems to work for selectors inside html.touch and html.no-touch.
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| navigator.maxTouchPoints; // works on IE10/11 and Surface
};
if ( is_touch_device() ) {
$('html').addClass('touch')
} else {
$('html').addClass('no-touch')
}
html.touch .hover-me:hover {
pointer-events: none !important;
cursor: pointer;
}
html.touch a:hover {
pointer-events: none !important;
cursor: pointer;
}
/* FOR THE DESKTOP, SET THE HOVER STATE */
html.no-touch .hover-me:hover {
width: auto;
color:blue;
background:green;
}
html.no-touch a:hover {
width: auto;
color:blue;
background:green;
}
However, my goal is to remove all :hover selectors. The * selector does not work for this purpose. It seems like I'm still struggling to make it work.
.hover-me:hover {
background: yellow;
}
html.touch .hover-me:hover {
pointer-events: none !important;
cursor: pointer;
}