communication leads to understanding, so ...

Standards compliant rollover script

While surfing the web looking for a nifty multi-level menu, I stumbled over a neat little rollover script made by Daniel Nolan. It adds mouse rollover code to images without the hassle of coding in extra parameters to each image in your document and what's more, it is standards compliant and should not invalidate your document.

The script makes use of the class attribute of the image tag; so every image that requires a mouseover effect should have the class="imgover" and look like this:

<img src="image" alt="some" title="what ever" class="imgover" />

You will need to create a rollover state for every image and name it exactly the same as the original, but give it the suffix _o. For example you have an image called button.gif, then you should name the rollover image button_o.gif, simple as that. Oh, and they must both reside in the same directory off course.

This is the code

function initRollovers() {

  if (!document.getElementById) return

    var aPreLoad = new Array();
    var sTempSrc;
    var aImages = document.getElementsByTagName('img');

    for (var i = 0; i < aImages.length; i++) {
    if (aImages[i].className == 'imgover') {
      var src = aImages[i].getAttribute('src');
      var ftype = src.substring(src.lastIndexOf('.'), src.length);
      var hsrc = src.replace(ftype, '_o'+ftype);

      aImages[i].setAttribute('hsrc', hsrc);

      aPreLoad[i] = new Image();
      aPreLoad[i].src = hsrc;

      aImages[i].onmouseover = function() {
      sTempSrc = this.getAttribute('src');
      this.setAttribute('src', this.getAttribute('hsrc'));
    }

    aImages[i].onmouseout = function() {
      if (!sTempSrc) sTempSrc = this.getAttribute('src').
          replace('_o'+ftype, ftype);
        this.setAttribute('src', sTempSrc);
      }
    }
  }
}

window.onload = initRollovers;

I tested this script in IE6, IE7, FF1.5, Netscape8, Opera9 all for Windows and it worked fine.

 |  | 25-01-2007

Bo Moulton wrote on 08-10-2007#1

I love the script, however, I am having trouble getting the cursor to be a "Hand" when you
roll over a link. As of now it is just a pointer. Can you help?

Bo Moulton
bomoulton@gmail.com

Hi Bo,
The scripts works fine for me in the browsers I mentioned, so maybe you assigned another style to the cursor in you css? Or maybe your Document Type Definition is not correct. I can’t think of anything else, sorry :(

©2006 - 2010 hbwConsultants - The Netherlands 

CMS  • XHTML • CSS • RSS