Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 606
Rich Bradshaw Avatar asked Sep 25 '22 13:09

Rich Bradshaw


2 Answers

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!

like image 184
Rich Bradshaw Avatar answered Oct 16 '22 07:10

Rich Bradshaw


All you need to do is bind touchstart on a parent. Something like this will work:

$('body').on('touchstart', function() {});

You don't need to do anything in the function, leave it empty. This will be enough to get hovers on touch, so a touch behaves more like :hover and less like :active. iOS magic.

like image 55
Razvan Cercelaru Avatar answered Oct 16 '22 06:10

Razvan Cercelaru