views:

331

answers:

4

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.

+1  A: 

Without device (or rather browser) specific JS I'm pretty sure you're out of luck.

Edit: thought you wanted to avoid that until i reread your question. In case of Mobile Safari you can register to get all touch events similar to what you can do with native UIView-s. Can't find the documentation right now, will try to though.

Joonas Trussmann
+1  A: 

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 onhover event using JavaScript.

var p = document.getElementsByTagName('p')[0];
p.onclick = function() {
 // Trigger the `onhover` event on the paragraph
 p.onhover.call(p);
};

This should work, as long as there's an onhover 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 ;)

Mathias Bynens
I didn't know about that onhover.call(p) bit, that's pretty cool. There's no off hover though...
Rich Bradshaw
A: 

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.

drawnonward
+2  A: 

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').bind('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!

Rich Bradshaw