JavaScript Made Easy: How to Add Multiple Image Rollovers to Your Web Page

In the previous lesson, I showed you how to do a simple image rollover. In the real world, however, it's rare that you'll ever have one rollover on a page. In this column, I'll show you how to add multiple rollovers to your Web page. Let's start by looking at the code, which you can see in action by clicking here:

Most of this code should look familiar if you read the previous JavaScript lesson about making a single rollover.

Let's start with the first part of the new code you'll be adding to the code for a single rollover:

<html>
<head>
  <title>Rollover Script</title>
  <script type="text/javascript" language="javascript">
    <!-- Hide script from older browsers

    if (document.images) {
      button1Red = new Image
      button1Blue = new Image
      button2Red = new Image
      button2Blue = new Image

      button1Red.src = "images/redButton1.gif"
      button1Blue.src = "images/blueButton1.gif"
      button2Red.src = "images/redButton2.gif"
      button2Blue.src = "images/blueButton2.gif"
    }

    function chgImg(imgField,newImg) {
      if (document.images) {
        document[imgField].src = eval(newImg + ".src")
      }
    }

  // End hiding script from older browsers -->
  </script>
</head>
<body bgcolor="#FFFFFF">
  <p><a href="#" onMouseover="chgImg('button1','button1Red')" onMouseout=
"chgImg('button1','button1Blue')"><img src="images/blueButton1.gif" width="113" height="33" border="0" name="button1" alt="button1"></a></p>
  <p><a href="#" onMouseover="chgImg('button2','button2Red')" onMouseout="chgImg('button2','button2Blue')"><img src="images/blueButton2.gif" width="113" height="33" border="0" name="button2" alt="button2"></a></p>
</body>
</html>

Most of this code should look familiar if you read the previous JavaScript lesson about making a single rollover.

Let's start with the first part of the new code you'll be adding to the code for a single rollover:

if (document.images) {
  button1Red = new Image
  button1Blue = new Image
  button2Red = new Image
  button2Blue = new Image

  button1Red.src = "images/redButton1.gif"
  button1Blue.src = "images/blueButton1.gif"
  button2Red.src = "images/redButton2.gif"
  button2Blue.src = "images/blueButton2.gif"
}

This code is similar to that of a single rollover except that this code includes four image objects instead of two -- that is, two image objects per rollover. Two image objects are needed because two different images are displayed per rollover: the on version and the off version. This part of the code creates the four new image objects, and then the src (read as "source") property of each is initialized to the location of the image file itself, relative to the Web page. As always, only use this code if the browser you're designing for supports image manipulation via JavaScript (that is, Netscape 3 or later and Internet Explorer 4 or later). So, this code starts off by checking to see if the document.images object exists.

Then add this line:

function chgImg(imgField,newImg) {

Here, you're creating your first JavaScript function -- a group of lines of code that you'll use often. Define a function by starting with the word function followed by the name of the function, in this case, chgImg. Functions can have any name that you want, as long as the name starts with a letter and contains only letters and digits. In this case, it's called chgImg, to remind us later that this bit of code changes images .

Inside the parentheses are zero or more parameters . A parameter is information that's passed into the function for the function to act upon, and the parameters are separated by commas. In this case, you're passing (giving the function) two parameters: imgField and newImg. Similar to functions, you can name parameters whatever you want with some exceptions. When the chgImg function is called (as you'll see later) it will always refer to the parameters by the names in parentheses.

Note the open brace after the parentheses: everything within the braces is what will be executed by your JavaScript.

After the line introducing the function, add:

if (document.images)

This line checks to see if the user's browser will understand the image object, which means that it has the ability to manipulate images via JavaScript (which is what we're trying to accomplish).

Now, the moment you've been waiting for. Here's the line to add to make the rollover actually happen:

document[imgField].src = eval(newImg + ".src")

Earlier I said that the imgChg function was passed two parameters: imgField and newImg. The former is the name of the image to be changed, and the latter is the image object that will replace it.

On the right side of the equals sign, we're creating an image object on the fly by using JavaScript's eval method. This method takes in a string, evaluates it (hence the name eval ), and returns a result of that string turned into an object. In this case, if newImg is the string "redButton", take that and add the string ".src" onto the end of it, resulting in the string "redButton.src". The eval method then evaluates that string and returns the actual image object redButton.src. This step gives us the image object that we can then use to replace the currently displayed image.

In order to actually change the image being displayed, set document["myButton"].src to redButton.src to cause the red version of myButton to appear. This assumes that there was an image named myButton on the page, and that redButton had been created as a new image and the src property had been set to the appropriate image file.

This section of code displays the images on the Web page:

<a href="#" onMouseover="chgImg('button1','button1Red')" onMouseout="chgImg('button1','button1Blue')"><img src="images/blueButton1.gif" width="113" height="33" border="0" name="button1" alt="button1"></a>

The first image (before rollover) has been given the name button1. This code says that the chgImg function is called by both the onMouseover and onMouseout event handlers, both of which pass 'button1' as their first parameter (the first item in each of the parentheses).

The second parameter (second item in each of the parentheses) is the version of the button to display after the event (the mouse rolling over the first image) has taken place, and so, onMouseover passes 'button1Red' in this place, showing 'button1Red' where 'button1Blue' used to be. And as you might expect at this point, the onMouseout event handler passes 'button1Blue' as its second parameter, which will cause the blue version of the button to be redisplayed when the cursor moves off of button1.

Here's where the second button comes in:

<a href="#" onMouseover="chgImg('button2','button2Red')" onMouseout="chgImg('button2','button2Blue')"><img src="images/blueButton2.gif" width="113" height="33" border="0" name="button2" alt="button2"></a>

This code looks similar to the previous piece. The only differences are in the name of the image itself (which is then passed as the first parameter to the imgChg function), and the appropriate red or blue image object for the second button, which is passed as the second parameter to imgChg.

Follow the instructions outlined in this lesson to add as many buttons to the page as you want. All you need to do is create two new image objects in the head of your Web page (and set them to the correct file names), and then add your anchor and img tags directly to the page.

DORI SMITH is coauthor of JavaScript for the WWW: Visual QuickStart Guide, 3rd Edition and author of Java for the WWW: Visual QuickStart Guide . In addition to writing, she has been programming for more than 20 years and conducts workshops at industry conferences.

Subscribe to the Apple @ Work Newsletter

Comments