Mittwoch, 22. März 2006

Teach Internet Explorer the :hover pseudo-class

The pseudo-class :hover is a great way to visually represent a change of state. We all know it well from links, the easiest example is to switch colors, so that the visitor knows when the mouse is over it.

The problem

Unfortunately, the a-tag is the only tag for which the Internet Explorer understands the :hover class. In order to produce better hover-effects, one could either pack everything related to inside an a-tag, for example:

<a href="index.html">Testlink
<span>with a description</span></a>

This method works fine if it’s just with span-tags. But imagine you have a header and some text or something like this. The appropriate code would be:

<a href="index.html">
  <h2>Heading</h2>
  <p>Description</p>
</a>

Well, good-bye validity, as this example is not valid – for example, the h2-Tag needs to be outside the a-Tag. So, we have to find another solution.

The solution

Instead of just using CSS, we make use of some JavaScript to produce the hover effect:

function hover() {
  var divs = document.getElementsByTagName("div");
    for(var q = 0; q < divs.length; q++) {
      if(divs[q].className == "entry") {
        divs[q].onmouseover = function() {
          this.className = "entryH";
        };
        divs[q].onmouseout = function() {
          this.className = "entry";};
        }
      }
    }
}

And the appropriate CSS-classes:

.entry { some formattings };
.entry { some formattings for hover };

Now, if you have a div-Element with a class "entry", it will be switched with the class "entryH" when hovering it. No more :hover needed, and it will be understood by Internet Explorer. This method has another advantage: If you switch background-images via :hover, they won't be cached, instead they'll be loaded every time the user hovers the element. With this solution, all images will be cached and no more little pauses are occuring.

2 Kommentare

  1. JSp

    This wasn’t teaching (or forcing) IE to accept the :hover psuedo-class. It is merely a hybrid (close to non-)CSS method. So the title of this tutorial should be, “Javascript method to remedy IE’s non-support of :hover pseudo-class” :) … I would hope there is a pure CSS hack somewhere.

Kommentar schreiben

SEOs brauchen es erst gar nicht probieren, Kommentare mit dem Zweck der kommerziellen Eigenwerbung (Links zu Shops, Firmen, o.ä.) sowie sinnloser Schrott werden ebenfalls als Spam markiert. Wenn ihr etwas völlig anderes beisteuern wollt, dann bitte über den normalen Kontakt.