Hover effect on touch devices with Modernizr

Here is the tip about how to check if a browser has touch capabilities and do something about it.

In our web application we have certain html divs that are hidden unless the mouse is over it (on:hover).

This is our initial css

.actions {

.actions:hover {

In touch devices, the behaviour of the hover is that the first touch will act as a hover, and then the user can take the action. This is not very useable, so we have decided that in touch devices everything has to be shown. Yeah it looks worse but it is more useable.

So we looked for a solution and found Modernizr, and good guides on how to configure it such as this one: http://html5doctor.com/using-modernizr-to-detect-html5-features-and-provide-fallbacks/

When the device accepts touch events, Modernizr will add a class .touch to the html. So then you can make use of it. We added this css code:

.touch .actions {
display: block;

By the way, if you would like to make a quick test to see if Modernizr is detecting the touch/no-touch feature, try out this code:

if (Modernizr.touch) {
alert('Touch Screen');
} else {
alert('No Touch Screen');

Another tip: I compiled a modernizr.js with just the feature detection that we need. this is:

Misc. > touch events

But, very important, do also add this other feature so that the class addition will work:

Extra > CSS Classes

This is the download page for Modernizr: http://modernizr.com/download/#-touch-cssclasses-teststyles-prefixes

And if you want to test the page features for touch devices from your Mac you can use the iOS simulator. Just follow this guide, you will have to install xCode: https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/iOS_Simulator_Guide/GettingStartedwithiOSStimulator/GettingStartedwithiOSStimulator.html

*** UPDATE ***
As Patrick adds on the comment below, you have to be aware that Modernizr does not detect if the device is touch enabled, but rather if the browser has touch capabilities. Nowadays some browsers report touch capabilities even if the underlying hardware cannot actually make use of them.