CSS, JavaScript and XHTML Explained

Estelle Weyl's Blog of quirks, random thoughts and funky finds discovered in day-to-day coding

 

hover pseudoclass for the iPhone December 28, 2008

Since you’re not hovering, there is no hover pseudo class on the iPhone. instead they have touch events. To simulate the :hover pseudo class, include javascript similar to this:

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
   myLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
   myLinks[i].addEventListener('touchend', function(){this.className = "";}, false);
}

and in your CSS add something similar to:

a:hover, a.hover { /* whatever your hover effect is */ }

Notes:

  • onTouchStart is similar to onMouseOver and onTouchEnd is similar to onMouseOut
  • You’ll likely want something more complex than simply removing the class on touch end. This is just a very simple example that will replace all classes on all your links with a "hover" class, which is probably not what you want. But you get the idea.
  • You can use this on all elements, not just links.

-Estelle Weyl

Note:

 

7 Comments for this post

 
Craig Says:

Awesome!! Touchstart works perfectly but I think my layout is getting in the way of touchend, sort of. Great job!

 
iphone/ipad网站开发技巧 Says:

[...] hover pseudoclass for the iPhone [...]

 
Felix Says:

This may be because this post is from 2008, but the :hover CSS pseudo-class works just fine on my iPod touch (iOS 3.1.2). The properties defined there are applied when touching the item.

 
Damian Says:

I don’t understand: What do I enter where it says, “/* whatever your hover effect is */”

Please note that I’m a newbie when it comes to CSS.

Thanks in advance for your help!

Leave a Reply