Better image rollovers
In these days of standards, the DOM and separating structure from presentation this is no longer good enough. Image rollovers are a presentational nicety—they add nothing to the underlying meaning of the document and as such I see no reason to pollute my markup with code to support them. I’m always on the lookout for fun new ways to use the DOM (see blockquote citations) so I took it upon myself to improve the situation. The first iteration of my improved rollover script, rollovers.js, is demonstrated here.
The approach I have taken is to give any images that are to have a rollover a CSS defined background image and a class attribute of “rollover”. The
rollovers.js script then finds all images with that class name and adds onmouseover and onmouseout events to them (using Scott Andrew’s addEvent function to avoid cross browser incompatibilities). When an image is rolled over, the image is replaced with a preloaded transparent gif allowing the background image to show through. The gif is switched back to the default image when the mouse moves away.
The script works fine in Mozilla 1.2, Phoenix 0.5 and IE6. It fails in Opera 7, thanks I think to problems dynamically adding new events in that browser. I would love to hear if it works in other browsers, especially Mac browsers such as IE 5 and Safari. Any suggestions on further improvements to the script would also be very welcome.