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.
OK, I've worked it out! It involves changing the CSS slightly and adding some JS.
Using jQuery to make it easy:
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:
with
And just for added usefulness, add this to your CSS as well:
To stop the browser asking you to copy/save/select the image or whatever.
Easy!
Easyest solution I found: I had some < span > tags with :hover css rules in them. I switched for < a href="javascript:void(0)" > and voilà. The hover styles in iOS started working.
Use can use CSS too, add focus and active (for IE7 and under) to the hidden link. Example of a ul menu inside a div with class menu:
It's late and untested, should work ;-)
My personal taste is to attribute the
:hover
styles to the:focus
state as well, like:Then with the following HTML:
And the following JavaScript:
To answer your main question: “How do I simulate a hover with a touch in touch enabled browsers?”
Simply allow ‘clicking’ the element (by tapping the screen), and then trigger the
hover
event using JavaScript.This should work, as long as there’s a
hover
event on your device (even though it normally isn’t used).Update: I just tested this technique on my iPhone and it seems to work fine. Try it out here: http://jsfiddle.net/mathias/YS7ft/show/light/
If you want to use a ‘long touch’ to trigger hover instead, you can use the above code snippet as a starting point and have fun with timers and stuff ;)
One way to do it would be to do the hover effect when the touch starts, then remove the hover effect when the touch moves or ends.
This is what Apple has to say about touch handling in general, since you mention iPhone.