Home > Articles > Open Source > Ajax & JavaScript

JavaScript for Web Professionals: Using Image Rollovers

  • Print
  • + Share This
Dan Barrett teaches you how to spruce up your site using image rollovers.
This chapter is from the book

You've gotten the ball rolling on the site and have shown that you've got what it takes to get the job done—now your boss wants you to wow him. He wants to make the site more dynamic and give it a little bit of "flash." He has checked out the competition's sites, and they all have image rollovers on theirs—JavaScript rollovers are used to swap an image with a different version of that image when the user moves the cursor over it. Conversely, when the user moves the cursor off of the image, the new image is replaced with the original. This technique is widely used on Web pages, and your boss feels this is just what your site needs to spruce it up.

The first thing to do is choose which graphics we want to be affected by the rollovers. The best place for image rollovers on most pages is on the main navigation images, and the Shelley Biotech site is no different (see Figure 2–1).

Figure 2-1FIGURE 2–1 Shelley Biotech homepage.


One of the designers has come up with a great graphic treatment for the rollovers (see Figure 2–2), and it's now up to you to implement them. There are three parts to creating an image rollover: Define the IMAGE objects, create the functions that will do the work, and insert the necessary JavaScript event handlers into your image and anchor tags. The first step in writing our script is the creation of the IMAGE objects.

Figure 2-2FIGURE 2–2 Image rollover sample.


Project I: Image Rollover Script

Creating and Inserting the Image Objects

Before we get to the creation of the image objects themselves, we must decide where to put our script. Because the rollovers will be on every page of the site, it makes sense to place our script into an external JavaScript file. That way, we only need to place it in a single location instead of on each page. We have already created an external JavaScript file called jsFunctions.js for one of our previous projects, so we can simply add our new script to that file. The home page already has the call to the external file, so we can just copy that <script> tag to all of the other pages on the site.

The first step in our script is to cloak for older browsers that don't support the IMAGE object, which is necessary for our rollover script. In Chapter 1 we learned how to use JavaScript to gather the browser and platform information. We could use a variation of that method in which we set up a bunch of if statements that test for every browser that doesn't support the IMAGE object; however, this would be loads of work. Fortunately for us, there is a simpler way. We can test if the user's browser supports rollovers using only a single if statement, as shown in the following lines of code:

  // Creation of the image objects
if (document.images) {
. . .
} 

In the preceding lines of code we used

document.images

as the condition in our if statement. The condition returns a value of true if the browser supports the IMAGE object and a value of false if it does not. By inserting our code within this if statement, we are in effect cloaking our code from browsers that cannot handle the script.

When an HTML page is loaded and the browser creates the objects that make up the JavaScript hierarchy, every image laid out on the page is made into an object and put into an array called images. This is the first time we have come across arrays, so let's take a quick look at what an array is and, in particular, the images array and how we are going to use it.

You can think of an array as a filing cabinet. Let's say you have a page with four images on it. When the browser reads the HTML file, it goes down the page, and when it reaches the first image, it creates an IMAGE object for it and stores it in the first drawer of our filing cabinet. When it reaches the second image, it again creates a new IMAGE object, and then puts it into the second drawer of the filing cabinet, and so on until each of the images on the page has its own IMAGE object, which is stored in its own drawer.

When the browser needs to reference any of those images, it knows in which drawer to look for each of them. You, too, can reference the array and the IMAGE objects held therein—there are two ways to do this. The first is to reference the location in the array at which the IMAGE object resides. The problem with this method is that if you add an image somewhere on the page, the position of all of the images below it will change. This will cause you to go through your whole script and make sure an image you were calling isn't now in a different position. The second way, which we use in this script, takes care of this problem.

If you specify a NAME attribute in your <img> tags, you can then reference that graphic in the array by the name that you have assigned to it. With this method, even if you add other graphics to the page, you will still be able to reference the IMAGE object the same way, and your script won't be adversely affected.

There are six navigation images that will be affected by our rollover script, so for each of those images, we need to assign a NAME attribute in the <img> tags.

   <a href="products.html">
<img src="images/products_off.gif" width=71 height=33
border=0 name="Products" alt="Products"></a>

   <a href="services.html">
<img src="images/services_off.gif" width=67 height=33
border=0 name="Services" alt="Services"></a>

   <a href="training.html">
<img src="images/training_off.gif" width=75 height=33
border=0 name="Training" alt="Training"></a>

   <a href="common.html">
<img src="images/common_off.gif" width=157 height=33
border=0 name="Common" alt="Common Good"></a>

   <a href="genetic.html">
<img src="images/news_off.gif" width=98 height=33
border=0 name="News" alt="Genetic News"></a>

   <a href="about.html">
<img src="images/about_off.gif" width=106 height=33
border=0 name="About" alt="About Shelley"></a>

In the preceding lines of HTML, we added a NAME attribute to each of the six <img> tags. The name for each is the first word of the category that the graphic represents. JavaScript is case-sensitive, so take notice that the first letter of each name is capitalized. Now that we have the names of these images squared away, we can move on to the creation of some new IMAGE objects that we will need for our script.

Because the images that we want to come up when the user rolls over one of the six graphics aren't explicitly placed on the page with HTML, we need to create two new IMAGE objects for each image we want to roll over. This will add these images to the images array and allow us to access their properties. Let's start by creating the IMAGE objects for the Products image.

  // Creation of the image objects
if (document.images) {
ProductsOn=new Image(71, 33);
. . .
} 

In this first line, we initialize a new IMAGE object by using an image constructor, the syntax for which is

New Image(width, height);

By putting the image constructor on the right-hand side of the assignment operator, and the name that we wish the IMAGE object to have on the left, we have just created a new IMAGE object called ProductsOn.

The naming of these new objects is very important to the operation of the script. The first part of the name should be the same as the name of the image to which it corresponds that is already on the page. For example, in this first line, we created an object to hold the location of the rolled over version of the Products graphic, so the name starts with Products. Because this object holds the rolled over version of the graphic, the second part of the name is On. When combined, we have a new object with the name ProductsOn. For each of the six navigation images, we need not only an object to hold the rolled over version of the graphic but one to hold a regular version of the graphic as well. This second object's name for our Products image will also start with Products but will end with Off. Let's add this new IMAGE object after our first one.

  // Creation of the image objects
if (document.images) {
   ProductsOn=new Image(71, 33);
   . . .
   ProductsOff=new Image(71, 33);
   . . .
} 

If you deviate from this naming convention, the functions that we will be writing won't know which IMAGE object to use for replacement, and you will get errors. We now have the two new IMAGE objects that we will need for the Products rollover, but at the moment they are empty. We need to assign actual images to them. We do this by assigning the location (URL) of the image to the source property of the IMAGE object, as follows:

  // Creation of the image objects
if (document.images) {
   ProductsOn=new Image(71, 33);
   ProductsOn.src="images/products_on.gif";

   ProductsOff=new Image(71, 33);
   ProductsOff.src="images/products_off.gif";
   . . .
} 

We have completed On and Off objects for the Products rollover, but we now have to create objects for each of the other five image rollovers. We do this using the same naming conventions that we used for our first objects.

  // Creation of the image objects
if (document.images) {
   ProductsOn=new Image(71, 33);
   ProductsOn.src="images/products_on.gif";

   ProductsOff=new Image(71, 33);
   ProductsOff.src="images/products_off.gif";


   ServicesOn=new Image(67, 33);
   ServicesOn.src="images/services_on.gif";

   ServicesOff=new Image(67, 33);
   ServicesOff.src="images/services_off.gif";


   TrainingOn=new Image(75, 33);
   TrainingOn.src="images/training_on.gif";

   TrainingOff=new Image(75, 33);
   TrainingOff.src="images/training_off.gif";


   CommonOn=new Image(157, 33);
   CommonOn.src="images/common_on.gif";

   CommonOff=new Image(157, 33);
   CommonOff.src="images/common_off.gif";


   NewsOn=new Image(98, 33);
   NewsOn.src="images/news_on.gif";

   NewsOff=new Image(98, 33);
   NewsOff.src="images/news_off.gif";


   AboutOn=new Image(106, 33);
   AboutOn.src="images/about_on.gif";

   AboutOff=new Image(106, 33);
   AboutOff.src="images/about_off.gif";
}
 . . . 

Creating the IMAGE objects in this manner also has another desired effect. When the browser creates the new IMAGE objects, it loads the images into its cache, thereby preloading it into memory. This preloading allows the image to display immediately upon rollover. It is important to keep this preloading in mind when creating your HTML pages—if you do not put Height, Width, and alt attributes into your <img> tags, some browsers will wait to display any of the page until all of the content and images are loaded into memory. You can run into some serious load times if you have a lot of IMAGE objects loading for rollovers in the background, so make sure you put all of the necessary tags into your HTML.

We have now created IMAGE objects for all of the graphics that we need to accomplish our rollovers. Our next step is the creation of the functions that will run our rollovers.

Image Rollover Functions

When the user rolls over one of our graphics, JavaScript event handlers call the functions we are going to write to actually perform the image replacements. Functions are an essential part of JavaScript; a function is a set of JavaScript statements that perform specific tasks. We cover both defining and calling functions in this example, but for now, let's concentrate on defining the functions we need for our rollovers. To define a function, you need four basic elements: the function keyword, a name for the function, a set of arguments that are separated with commas, and the statements that you want the function to execute.

We need to create two functions for our rollovers to work: one that switches to the On graphic when we roll onto an image and another to switch back to the Off graphic when we roll off the image. Generally, you should define the functions for a page in the <head> of your HTML, so let's start our functions right after our IMAGE objects.

// function to turn on rolled over graphic
function on(pic) {
. . .
}

The first step in defining a function is to call the function keyword followed by the name of our function; in this case, we'll call it On. Following the name, within its set of parentheses, we need to put a list of variables separated by commas, one for each argument we want to pass into the function. These variables will let us pass values into our function from the event handlers that call the function. We need to pass only a single argument into our function; we'll use the variable pic to hold that argument.

Next, we need to insert the set of instructions that we want the function to execute—these statements are enclosed within curly brackets.

// function to turn on rolled over graphic
function on(pic) {
   if (document.images) {
    document.images[pic].src=eval(pic + "On.src");
   }
}

The first of the statements that we want the function to execute is an if statement that will check for older browsers. If the browser supports the IMAGE object, the next line will be executed. In this line, we tell the browser to replace the source of the image that is being rolled over with the source of the On version of the graphic. A lot is happening in this line, so let's break it down into smaller parts. First, let's look at the left-hand side of the assignment operator.

document.images[pic].src

We reference the source property of the image located at the position in the images array that has the value of the variable pic, so let's say the value of pic is Products. We would be referencing the source property of the Products IMAGE object and assigning it the value passed to it from the right-hand side of the assignment operator.

If we explicitly reference the images, like so:

document.product.src 

we need separate functions for every image we wanted a rollover for—not the most efficient way to code. When scripting, you always should think about how you can most efficiently write your code. Any time you can use variables in this way, it will save you a lot of time and trouble. There are, however, occasions when you will want to call a specific image every time the function is called, and the preceding line of code is an example of how to do that.

On the right side of the operator, we use the eval() statement to combine the value of pic with a string to create a new value to assign as the source of the image being rolled over.

eval(pic + "On.src");

If the value of pic is Products, the eval() statement will return ProductsOn.src, and the value of the source of the ProductsOn IMAGE object will be assigned to the source of the Products IMAGE object. When this happens, the image on the page will change to the On image until the user rolls off.

When the user rolls off the image, another function will be called. This is the second function that we have to create—let's call this function Off.

// function to turn off rolled over graphic

function off(pic) {
   if(document.images) {
   document.images[pic].src= eval(pic + "Off.src");
  }
}

This function should look similar to your On function; in fact, the only difference is that the second half of what is being evaluated on the right-hand side of the assignment operator is Off.src instead of On.src. Therefore, when this line is evaluated, it will assign the source of the ProductsOff IMAGE object to be the source of the Products IMAGE object, thereby returning the image to its regular look.

Our functions are now complete and we are almost finished with the script. All that's left for us to do is to put the proper JavaScript event handlers into our HTML code.

Creating and Inserting the Event Handlers

You will find that most things in JavaScript are event-driven—events generally are the result of some action on the part of the user. If a user rolls over a link or changes the value of a text field, these would constitute events. To make use of these events with your JavaScript, you must define an event handler to react to these events. There are many predefined event handlers that you can use for this purpose; the two that we use for our rollovers are onMouseOver and onMouseOut. Let's first see what our existing HTML looks like without the event handlers.

<a href="products/index.html">
<img src="images/products_off.gif" width=71 height=33
border=0 name="Products" alt="Products"></a>

For our purposes, we must add the event handlers to the ANCHOR tag. First, we add the onMouseOver handler.

<a href="products/index.html"
onMouseOver="on('Products'); return true;">

When an event handler is called, it executes any JavaScript statements that follow the handler. We enclose these statements in quotes and separate them with semicolons. The first thing we want our event handler to do is call our On function. To call a function, you simply call its name and enclose any arguments you wish to pass along to the function in parentheses separated by commas.

on('Products');

The preceding statement calls the On function and passes it the value Products; again, we are passing it Products because that is the name of the image that we want our function to affect.

Another often seen addition to rollovers is the display of a relevant phrase in the browser's status bar. To do this, we add another statement to our event handler.

<a href="products/index.html" onMouseOver="on('Products');
window.status='Products'; return true;">

By calling on the WINDOW object's status property, we can display text in the browser's status bar by assigning it a new value. The last addition that we need to make to our event handler is the following statement:

return true;

This tells the JavaScript engine that this is the end of what needs to be executed in the event handler and it can go on with the rest of its business.

Well, one event handler down, and one more to go. Let's add our onMouseOut handler to take care of things when the user rolls off an image.

<a href="products/index.html" onMouseOver="on('Products');
window.status='Products'; return true; " onMouseOut="off('Products');
window.status=' '; return true;">

For our onMouseOut handler, we call the Off function, again passing it the name of the graphic that we want to affect. To turn off the phrase that we put into the status bar, we now reset the window.status to a blank value and then leave the handler with the return statement.

Now that we have inserted the event handlers for the Products image, we need to put some in for the rest of the images we want to have rollovers for. The syntax will be the same, the only difference being that you have to change the value that you are passing to the functions to the name of the graphic that you want to be changed.

<a href="products/index.html" onMouseOver="on('Products');
window.status='Products'; return true; " onMouseOut="off('Products');
window.status=' '; return true;"><img src="images/products_off.gif"
width=71 height=33 border=0 name="Products" alt="Products"></a>

<a href="services/index.html" onMouseOver="on('Services');
window.status='Services'; return true; " onMouseOut="off('Services');
window.status=' '; return true;"><img src="images/services_off.gif"
width=67 height=33 border=0 name="Services" alt="Services"></a>

<a href="training/index.html" onMouseOver="on('Training');
window.status='Training'; return true; " onMouseOut="off('Training');
window.status=' '; return true;"><img src="images/training_off.gif"
width=75 height=33 border=0 name="Training" alt="Training"></a>

<a href="common/index.html" onMouseOver="on('Common');
window.status='Common Good Projects'; return true; "
onMouseOut="off('Common'); window.status=' '; return true;"><img
src="images/common_off.gif" width=157 height=33 border=0
name="Common" alt="Common Good"></a>

<a href="genetic/index.html" onMouseOver="on('News');
window.status='Genetic News'; return true; "
onMouseOut="off('News'); window.status=' '; return true;"><img
src="images/news_off.gif" width=98 height=33 border=0
name="News" alt="Genetic News"></a>

<a href="about/index.html" onMouseOver="on('About');
window.status='About Shelly Biotechnologies'; return true; "
onMouseOut="off('About'); window.status=' '; return true;"><img
src="images/about_off.gif" width=106 height=33 border=0
name="About" alt="About Shelley"></a>

Reviewing the Script

We should now have all of the elements that we need to get our Web site up and running with some great rollovers. Let's take a look at the completed script and go over what we did in each section.

First, we created the IMAGE objects that we need in our script.

  // Creation of the image objects
if (document.images) {
   ProductsOn=new Image(71, 33);
   ProductsOn.src="images/products_on.gif";

   ProductsOff=new Image(71, 33);
   ProductsOff.src="images/products_off.gif";


   ServicesOn=new Image(67, 33);
   ServicesOn.src="images/services_on.gif";

   ServicesOff=new Image(67, 33);
   ServicesOff.src="images/services_off.gif";


   TrainingOn=new Image(75, 33);
   TrainingOn.src="images/training_on.gif";

   TrainingOff=new Image(75, 33);
   TrainingOff.src="images/training_off.gif";


   CommonOn=new Image(157, 33);
   CommonOn.src="images/common_on.gif";

   CommonOff=new Image(157, 33);
   CommonOff.src="images/common_off.gif";


   NewsOn=new Image(98, 33);
   NewsOn.src="images/news_on.gif";

   NewsOff=new Image(98, 33);
   NewsOff.src="images/news_off.gif";


   AboutOn=new Image(106, 33);
   AboutOn.src="images/about_on.gif";

   AboutOff=new Image(106, 33);
   AboutOff.src="images/about_off.gif";
}

Here are the steps we took in creating the needed IMAGE objects:

  1. We set up cloaking for browsers that do not support IMAGE objects.

  2. We added the NAME attribute to the six images that we want to put rollovers on.

  3. We created a set of two new IMAGE objects for each of the six images that will be affected by our rollover script.

  4. We assigned each of the IMAGE object's source property the location of the proper image file.

Next, we created the functions that run our rollovers.

// function to turn on rolled over graphic
function on(pic) {
  if (document.images) {
   document.images[pic].src=eval(pic + "On.src");
  }
 }

// function to turn off rolled over graphic
function off(pic) {
   if(document.images) {
   document.images[pic].src= eval(pic + "Off.src");
  }
 }

Here are the steps we took in creating the rollover functions:

  1. We first created a new function called On that changes the image the user is currently over to the rolled over version of that graphic.

  2. We wrote a function called Off that changed the graphic back to its default state when the user rolled off of it.

Finally, we made the necessary changes to the <a href> tags in the existing HTML.

<a href="products/index.html" onMouseOver="on('Products');
window.status='Products'; return true; " onMouseOut="off('Products');
window.status=' '; return true;"><img src="images/products_off.gif"
width=71 height=33 border=0 name="Products" alt="Products"></a>

<a href="services/index.html" onMouseOver="on('Services');
window.status='Services'; return true; " onMouseOut="off('Services');
window.status=' '; return true;"><img src="images/services_off.gif"
width=67 height=33 border=0 name="Services" alt="Services"></a>

<a href="training/index.html" onMouseOver="on('Training');
window.status='Training'; return true; " onMouseOut="off('Training');
window.status=' '; return true;"><img src="images/training_off.gif"
width=75 height=33 border=0 name="Training" alt="Training"></a>
<a href="common/index.html" onMouseOver="on('Common');
window.status='Common Good Projects'; return true; "
onMouseOut="off('Common'); window.status=' '; return true;"><img
src="images/common_off.gif" width=157 height=33 border=0
name="Common" alt="Common Good"></a>

<a href="genetic/index.html" onMouseOver="on('News');
window.status='Genetic News'; return true; "
onMouseOut="off('News'); window.status=' '; return true;"><img
src="images/news_off.gif" width=98 height=33 border=0
name="News" alt="Genetic News"></a>

<a href="about/index.html" onMouseOver="on('About');
window.status='About Shelly Biotechnologies'; return true;"
onMouseOut="off('About'); window.status=' '; return true;"><img
src="images/about_off.gif" width=106 height=33 border=0
name="About" alt="About Shelley"></a>

Here are the steps we took to insert the event handlers into the HTML:

  1. We added the onMouseOver event handlers to each of the six images' <a href> tags. Within that handler we called the On function, passing it the name of the graphic that we were rolling over, changed the status bar to display a new message, and added the return command to exit the handler.

  2. We added the onMouseOut event handlers to each of the six images' <a href> tags. Within that handler we called the Off function, passing it the name of the graphic that we were rolling over, reset the status bar to nothing, and added the return command to exit the handler.

We introduced several new aspects of JavaScript in this first script, including

  • A new method of cloaking that looks for browsers that support specific objects that are needed in your script.

  • An introduction to arrays, specifically the images array.

  • How to create new IMAGE objects and how to change their source property.

  • How to create a function.

  • The concept of event handlers and how to use two of them: onMouseOver and onMouseOut.

  • How to change the message being displayed in the status bar of the browser window.

  • + Share This
  • 🔖 Save To Your Account