Better image rollovers
19th January 2003
When browsing through other site’s source code, some of the ugliest HTML occurs when the site uses one of the most basic javascript effects: The image rollover. There are a myriad of these scripts available for free on the web, but as far as I can tell every single one of them requires event handling code to be added to the markup of the page.
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.
More recent articles
- Gemini 2.0 Flash: An outstanding multi-modal LLM with a sci-fi streaming mode - 11th December 2024
- ChatGPT Canvas can make API requests now, but it's complicated - 10th December 2024
- I can now run a GPT-4 class model on my laptop - 9th December 2024