JSFiddle - React, Tailwind, and code Playground
HTML
<a href="#">hover me</a>
<p class="info">
Hover effects <span class="on">on</span><span class="off">off</span>
</p>
CSS
a {
color: grey;
font-size: 40px;
}
/* all :hover rules need to be prepended with body.hasHover */
body.hasHover a:hover {
color: blue;
}
/**
* Helpers for this example.
*/
.on { display: none; }
body.hasHover .on { display: inline; }
body.hasHover .off { display: none; }
JavaScript
function watchForHover() {
// lastTouchTime is used for ignoring emulated mousemove events
// that are fired after touchstart events. Since they're
// indistinguishable from real events, we use the fact that they're
// fired a few milliseconds after touchstart to filter them.
let lastTouchTime = 0
function enableHover() {
if (new Date() - lastTouchTime < 500) return
document.body.classList.add('hasHover')
}
function disableHover() {
document.body.classList.remove('hasHover')
}
function updateLastTouchTime() {
lastTouchTime = new Date()
}
document.addEventListener('touchstart', updateLastTouchTime, true)
document.addEventListener('touchstart', disableHover, true)
document.addEventListener('mousemove', enableHover, true)
enableHover()
}
watchForHover()