Rollover images with unobtrusive DOM scripting
There are about a million different scripts out there for doing JavaScript rollover images. Most of them however, aren't very good. They often require multiple functions... one to preload the images, one to swap them on rollover, and another to swap them back. Worse still, they usually involve inserting JavaScript event handlers into your HTML code.
Just look at the HTML code inserted by Adobe Dreamweaver's rollover function:
<a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('myImage','','images/myimage_o.jpg',1)"><img src="images/myimage.jpg" name="myImage" border="0" id="myImage" /></a>
This code is obtrusive and difficult to manage. Wouldn't it be great if you could just do something simple, like adding a CSS class, to make the rollovers work automatically? By using some scripting with the Document Object Model you can do that quite easily.
Here's a great rollover script written by Daniel Nolan that will allow us to greatly simplify our code. Take a look the HTML code needed to do the rollovers using this method.
<a href="#"><img src="images/myimage.jpg" class="imgover" /></a>
This is definitely much cleaner and easier. All we need to do is add the class="imgover" to our img tag and the script does the rest. When the page loads, the JavaScript looks through all of the img tags on the page. For each img tag it finds with the "imgover" class, it will dynamically add the onmouseover and onmouseout events to replace the images. It automatically looks for an image of the same name with "_o" at the end for the rollover. So if your main image were named myimage.jpg, you'd name the rollover image myimage_o.jpg.
That's all there is to it. Quick, easy, standards-compliant rollover images.
Download the rollover.js file.
Leave a comment