Roll Your Own Rollover Scripts

Part 1

This page is designed to show you how a JavaScript rollover works. Instead of bloating your page size with unnecessary code, you can insert streamlined code of your own. View source on this page to see the code, and feel free to copy it.


The button above uses two images:

JavaScripts Index

The button above uses two images:

Step 1 (below): List the images on the page and give them simple variable names, such as img1 and img2.
img1 = new Image(186,95);
img1.src = "images/start.jpg";
img2 = new Image(153,105);
img2.src = "images/indexbutton.gif";
img3 = new Image(186,95);
img3.src = "images/startglow.jpg";
img4 = new Image(153,105);
img4.src = "images/indexbutton_on.gif";
Step 2: Include a function that will change the image when the function is invoked.
function changeimage(imgx,placex) {
  if (document.images) {
    document.images[placex].src = eval(imgx + ".src");
Step 3: Modify the A HREF tag (which makes the image act as a link) to include an onMouseOver instruction (using the function from Step 2 above) and an onMouseOut instruction, also using the function.
<a href="index.htm"
  onMouseOut="changeimage('img2','daisy');"><img   src="images/indexbutton.gif"
  name="daisy" alt="JavaScripts Index" width="153" height="105"   border="0"></a>

Using the NAME Attribute

Notice how the "place" of the image on the page is labeled with the NAME attribute in the IMG tag.

  • The placeholder NAME ("daisy" in the example above) is used in the JavaScript function that changes the image.
  • The most common error in creating rollovers: You forget to include NAME in the IMG tag.
  • Why "daisy"? No reason. The NAME can be any name you choose.
  • Each image on the page should have a unique placeholder NAME.
One of the nicest things about this script is that you can use it to change a lot of separate instances of one graphic (e.g. a bullet or pointer) AND to change an image in a different location on the page (e.g. show a picture when a button is moused over). See examples of these effects.
> Return to JavaScripts index