How do I simulate a hover with a touch in touch enabled browsers?

Rich Bradshaw picture Rich Bradshaw · May 17, 2010 · Viewed 206.9k times · Source

With some HTML like this:

<p>Some Text</p>

Then some CSS like this:

p {
  color:black;
}

p:hover {
  color:red;
}

How can I allow a long touch on a touch enabled device to replicate hover? I can change markup/use JS etc, but can't think of an easy way to do this.

Answer

Rich Bradshaw picture Rich Bradshaw · May 23, 2010

OK, I've worked it out! It involves changing the CSS slightly and adding some JS.

Using jQuery to make it easy:

$(document).ready(function() {
    $('.hover').on('touchstart touchend', function(e) {
        e.preventDefault();
        $(this).toggleClass('hover_effect');
    });
});

In english: when you start or end a touch, turn the class hover_effect on or off.

Then, in your HTML, add a class hover to anything you want this to work with. In your CSS, replace any instance of:

element:hover {
    rule:properties;
}

with

element:hover, element.hover_effect {
    rule:properties;
}

And just for added usefulness, add this to your CSS as well:

.hover {
-webkit-user-select: none;
-webkit-touch-callout: none;        
}

To stop the browser asking you to copy/save/select the image or whatever.

Easy!