How to (cheaply) prevent :hover for touch

2015-05-27 | #css, #javascript, #solution, #webdev

The way :hover is handled on touch devices, especially on iOS, is unfortunate to say the least. Often you'll want to get rid of those effects for good on those devices.

A cheap and lazy way of doing this, not requiring to parse whole css sheets and keeping the flexibility to apply the hover prevents on selected elements (those that don't redirect for example) are simple css classes.

Eiter you generelly try to detect a touch context, by adding a class to your body or HTML after having checked for touch properties in the document:

JS:

if( document.createTouch ){

$('body').addClass('touch');

}

CSS:

body:not(.touch) .element:hover {

color: red;

}

Another possibility, which works a little bit better with touch emulation like in Chrome (which does not have createTouch atm) would be to set an element class on touchstart, which all touch contexts definitely have:

JS:

$(selector).on('touchstart', function(){

$(this).addClass('touch');

});

CSS:

.element:not(.touch):hover {

color: red;

}

If you want to save the hover effect in a touch friendly way you'll not get around more complex JS-handling, which even may differ from element to element depending on what you're trying to achieve. A CSS-only menu is a completely different thing from making a link blink on touch.