JavaScript Made Easy: How to Make a Simple Image Rollover

The most commonly used JavaScript effect on the Web is the image rollover. For the one person with access to the Web who's never seen one before, an image rollover happens when you move your cursor over an image, and voila! the image changes.

Here's what a rollover looks like. Move your cursor over the blue button below to see it in action.

Many people who have been happily coding HTML by hand start to think about buying a WYSIWYG (what you see is what you get) HTML editor when they start trying to create their first image rollover. Thankfully, using JavaScript to create this effect isn't that difficult. In this article, I'm going to show you how to write the JavaScript code for a rollover, step by step. Here's what the final code looks like.

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

if (document.images) {
offButton = new Image
onButton = new Image

offButton.src = "images/blueButton.gif"
onButton.src = "images/redButton.gif"
else {
offButton = ""
onButton = ""

document.myButton = ""

// End hiding script from older browsers -->
<body bgcolor="#FFFFFF">
<a href="#" onMouseover="document.myButton.src=onButton.src" onMouseout="document.myButton.src=offButton.src"><img src="images/blueButton.gif" alt="button" width="119" height="25" border="0" name="myButton"></a>

To start, you'll need two identically sized, nontransparent buttons. (In this example, I've called them blueButton.gif and redButton.gif.) I'm going to show you how to display a blue button that changes color (to red) when the cursor moves over the button.

For this example, I'm assuming that you've already tried "Your First Script." I'm not going to explain the parts of the above HTML that I covered in that article, so if you think this is too advanced, you might want to go back and review those concepts again.

Start with the code I outlined in "Your First Script," and add just one image to the bottom of the page:

<img src="images/blueButton.gif" alt="button" width="119" height="25" border="0" name="myButton">

The only differences you should see between this and the garden-variety image tags you've been adding to your HTML all along is a new attribute: name. JavaScript uses the value of the name attribute (in quotes directly after name= ) so it can refer to this image later. In this case, you're going to name this image myButton, which will later be referred to as document.myButton. Names can't have spaces or start with numbers; beyond those limitations, you can call them just about anything you'd like.

Up at the top of the page, inside the <head> section, is a <script> section that contains the JavaScript code that sets up our rollover effect. Let's go through it a little at a time.

To get started, first add:
if (document.images) {

This line sets up the whole rollover magic. In order for a browser to display image rollovers, it needs to be able to understand JavaScript, and how to manipulate images. Some older browsers knew a little about JavaScript but couldn't handle image effects. This line checks to see if the JavaScript code can detect any images on the page.

Now, see that brace ( { ) at the end of the line? It starts a section of code, and that code (up until the closing brace) only runs if the code found the image(s) on the page. If the JavaScript can't handle images, everything in the first set of braces will be skipped, and everything in the second set of braces (those following the else ) will execute instead.

The next line is:
offButton = new Image onButton = new Image

Assuming that you have a browser that can understand JavaScript, create two image objects and name them offButton and onButton, respectively. An image object isn't always an image displayed on the screen when the page first loads. Instead, it can be an image, such as redButton.gif, that your JaveScript code grabs and displays only when the user performs a particular action. Here, you'll need two image objects for the two different versions of the button.

offButton.src = "images/blueButton.gif" onButton.src = "images/redButton.gif"

This is where the image objects stored for later on learn about the actual physical files they're associated with. In each case, set the src (read: "source") property of the image object to the folder in which the image is located. In this example, the off version of the button is set to the blue version of the image, and the on version of the button is set to the red version of the image. So now, I've showed you how to map the onButton image to the redButton.gif, and the offButton image to the blueButton.gif.

Have you ever been to a Web site where you move the cursor over an image, and suddenly a new image starts to download? A properly written image rollover won't do that: it will precache the images, which means the JavaScript will be written so it downloads all the images that might be displayed into the browser's cache when the page first loads. Then, if the user moves the cursor over a button, the new version will display immediately.

These two lines handle the precaching for you. As long as you refer to those images by the names of the image objects that JavaScript recognizes, the new images will display immediately.

offButton = "" onButton = ""

document.myButton = ""

You should always add these lines so that older browsers that don't understand much JavaScript won't give viewers an error. However, they still won't display the rollover.

Basically, you have to trick older browsers into accepting the minimum code necessary to load the page smoothly. The dummy variables (those characters within the quotation marks) are set to zero-length strings , or in other words, nothing at all. In this case, the three variables that the browsers need to recognize are offButton (the off version of the image), onButton (the on version of the image), and document.myButton (the image that's actually displayed in the browser).

<a href="#" onMouseover="document.myButton.src=onButton.src" onMouseout="document.myButton.src=offButton.src">

This is the last piece of the puzzle: the anchor tag around the img tag. It has two new attributes: onMouseover and onMouseout. These are JavaScript event handlers , which means that when an event happens, such as moving the cursor over an image, JavaScript will catch it and do whatever you've asked it to do. More event handlers will be covered in subsequent articles. (An event is any action that triggers a JavaScript.)

When the cursor moves over the image, the onMouseover event handler is triggered. That causes the line of code document.myButton.src=onButton.src to run. Remember that because we named our image myButton, we created a new image object document.myButton. In order to change the image that's displayed, we need to update the src property of this image. Because this is the moused-over version, we set document.myButton.src to onButton.src, the red (on) version of the button image.

When the cursor moves off the image, the onMouseout event handler is triggered. That causes the line of code document.myButton.src=offButton.src to run. As you'd expect by now, it sets document.myButton.src to offButton.src, the blue (off) version of the button image.

If you have a JavaScript-savvy browser that doesn't understand images, it will still catch those event handlers. It then tries to set document.myButton.src to offButton.src (or onButton.src, as the case may be).

This code can be used to handle multiple buttons on a page, of course. You just need to give each button a name (using the name attribute of the img tag), and create two new image objects per new button in the header script. And make sure that all those names are unique: one of the main errors that occurs when you copy and paste a bunch of code to duplicate existing scripts is that you can forget to change the names of the images to reflect the new ones you wish to use.

Now that you've seen how simple adding a rollover image can be, aren't you glad you didn't spend several hundred dollars on a WYSIWYG tool? On the other hand, those expensive programs do try to give you your money's worth: a page such as the one I've just described that is created with a tool would result in at least three times the code, with no extra benefit. This way, your code is cleaner and your page loads faster. And best of all, you know how it works.

DORI SMITH is co-author 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.

1 2 Page 1
Shop Tech Products at Amazon