How to prevent sticky hover effects for buttons on touch devices

Solution 1:

Since this part of CSS Media Queries Level 4 has now been widely implemented since 2018, you can use this:

@media (hover: hover) {
    button:hover {
        background-color: blue;
    }
}

Or in English: "If the browser supports proper/true/real/non-emulated hovering (e.g. has a mouse-like primary input device), then apply this style when buttons are hovered over."

For browsers that do not have this implemented (or didn't at the time of this original answer), I wrote a polyfill to deal with this. Using it, you can transform the above futuristic CSS into:

html.my-true-hover button:hover {
    background-color: blue;
}

(A variation on the .no-touch technique) And then using some client-side JavaScript from the same polyfill that detects support for hovering, you can toggle the presence of the my-true-hover class accordingly:

$(document).on('mq4hsChange', function (e) {
    $(document.documentElement).toggleClass('my-true-hover', e.trueHover);
});

Solution 2:

You can remove the hover state by temporarily removing the link from the DOM. See http://testbug.handcraft.com/ipad.html


In the CSS you have:

:hover {background:red;}

In the JS you have:

function fix()
{
    var el = this;
    var par = el.parentNode;
    var next = el.nextSibling;
    par.removeChild(el);
    setTimeout(function() {par.insertBefore(el, next);}, 0)
}

And then in your HTML you have:

<a href="#" ontouchend="this.onclick=fix">test</a>

Solution 3:

This is a common problem with no perfect solution. Hover behavior is useful with a mouse and mostly detrimental with touch. Compounding the problem are devices which support touch and mouse (simultaneously, no less!) like the Chromebook Pixel and Surface.

The cleanest solution I've found is to only enable hover behavior if the device isn't deemed to support touch input.

var isTouch =  !!("ontouchstart" in window) || window.navigator.msMaxTouchPoints > 0;

if( !isTouch ){
    // add class which defines hover behavior
}

Granted, you lose hover on devices which may support it. However, sometimes hover impacts more than the link itself, e.g. perhaps you want to show a menu when an element is hovered. This approach allows you to test for the existence of touch and perhaps conditionally attach a different event.

I've tested this on the iPhone, iPad, Chromebook Pixel, Surface, and a variety of Android devices. I can't guarantee that it will work when a generic USB touch input (such as a stylus) is added to the mix.

Solution 4:

You can override the hover effect for devices that don't support hover. Like:

.my-thing {
    color: #BADA55;
}

.my-thing:hover {
    color: hotpink;
}

@media (hover: none) {
    .my-thing {
        color: #BADA55;
    }
}

Tested and verified on iOS 12

Hat tip to https://stackoverflow.com/a/50285058/178959 for pointing this out.