How to use the DOM for :hover

posted April 22nd, 2005, no comments, tagged

Yup, Jeremy Keith is completely right when he says that :hover is behavioural. That’s why I’m going to explain here how you should do :hover via the DOM. That’s right… I’m going to tell you!

Okay, so first we grab all the links on the page. We’ll do this on onload. I’m actually going to cheat a bit with the events, but I hope you’ll forgive me:

window.onload = function(){
    var links = document.getElementsByTagName("a");
    for(var i = 0; i < links.length; i++){
        links[i].onmouseover = function(){
            this.className += "hover"; // sorry, no support for multiple classNames here
        };

        links[i].onmouseout = function(){
            this.className = this.className.replace(/\bhover\b/, "");
        };
    };
    links = null; // look how I evaded memory leaks here!
};

And the CSS:

a.hover {
    text-decoration: none;
    font-weight: bold;
}

Ahhh.. that’s so much better. Now we have seperated style and behaviour completely. Time for some well deserved rest now.

You didn’t think I was serious about this, did you?