Have you ever seen an image move, change color, or even “pop out” when you place the mouse pointer over it? You were probably looking at a JavaScript rollover. (For an example, point at the eye image in this page’s headline.)
On this page we’ll cover the rollover basics. (A more extensive tutorial is available from Doc JavaScript).
Let’s begin
Please review JavaScript basics before beginning this exercise.
- In your Student folder, create a folder called rollo
- Inside the rollo folder, create an images folder
- Download images.zip to your local disk
- Unzip images.zip to the rollo/images folder.
You’ll probably want to work on these files in NoteTab, which allows you to quickly switch between several documents.
The document.images object
Remember, JavaScript is an object-based language. One of the key JavaScript
objects is the document
object. Any page loaded by
a browser is represented by its corresponding document
object in JavaScript.
document.images
is a property of document
as well as an object in its own right. The document.images
object represents the images that are embedded in a given web page using the
IMG
tag. Consider the following HTML tag:
<IMG SRC="something.gif"
ALT="picture of something" NAME="something"
HEIGHT="100" WIDTH="100">
Assume that this is the third IMG
element in the
document. In JavaScript, you can refer to it in one of the following ways:
array notation: document.images[2]
Counting begins at 0 in JavaScript, so: 0, 1, 2. If you later insert an image
in front of one called by your script, you will have to change the array notation.
property notation: document.images.something
The image name something is supplied by the name
attribute of the IMG
element.
shortcut notation: document.something
This will cause problems only if some other object in this document (such
as a form or table) is also named something.
JavaScript:The document.images.length
property
This property holds the actual number of images on the page. If there are
10 images on a page, the last of them would be (in array notation) document.images[9]
but the value of document.images.length
would be
10.
Backward compatibility
Some JavaScript-capable browsers do not support the document.images
object. Very few people use such old browsers, but it is easy to accommodate
them with a simple if statement.
JavaScript: Testing for old browsers
if (document.images) {
Rollover code goes here...
}
This statement tests the browser by querying whether the document.images
object exists. If it does not, then document.images
is null, so it evaluates to false and the browser
ignores all of the code following the if
statement - in this
case, everything between {
and }
.
Why is this important? It avoids crashing those few browsers that support
JavaScript but not the Image
object.
A simple rollover
In NoteTab (or another text editor) create a new web page.
- Save the new page as gadgets.html in the rollo folder.
- Give it the title "Gadgets".
- The external stylesheet will be "main.css". In other words, put this in
the
HEAD
element:
<LINK rel="stylesheet"
type="text/css" href="main.css"> - In the body, type:
<h1>Gadgets</h1>
and save the page. - Save a copy of this page as widgets.html.
- Change the
title
andH1
content from "Gadgets" to "Widgets".
These will be the target pages for hyperlinks you are about to create. Now for the next step:
- Create another web page. Save it as index.html in the rollo folder.
- Give it the title "Welcome to Rollo's Gadgets and Widgets".
- Type the following in the body:
<h1>Rollo's Gadgets and Widgets</h1>
<h2>Your online source for hard-to-find stuff</h2>
- Now put a script container in the head.
- Save the page.
[Lost? Here’s the cheat sheet.]
Next step: Creating an Image object in JavaScript.
JavaScript: Creating an instance of the Image object
Creating an Image
object is as simple as creating
any other object or variable. Just type:
var variableName = new Image();
where variableName is a unique name of your choice.
Next, to preload an image so it will be instantly available when
needed:
variableName.src = "imageURL.gif"
Here’s the key to creating an image rollover: Any IMG
tag (HTML) can be associated with more than one Image
object (JavaScript). When the user points at the IMG
,
we swap one Image
for another Image
.
When the user’s mouse moves away from the IMG
,
we swap the Image
back.
So a JavaScript rollover requires at least two images, one for each Image
object. The images must be the same size because both will occupy
the same space on the page. For this exercise we’ll use the following
button images:
blank.gif ![]() |
active.gif ![]() |
- Add IMG tags for each of these images to index.html in the rollo folder. The images are already located in rollo/images; they are each 30 pixels wide and 30 pixels high. [Show me how]
- OK, now turn each image into a hyperlink. The first will point to gadgets.html, the second to widgets.html. [Show me how]
- Rollover images must have a unique name, which can be assigned with the
name
attribute. Give the first image the name button. While we’re at it, let’s add some text alongside each button. [Show me how]
Now to write the JavaScript rollover code. You can copy and paste it from the following example.
JavaScript: Rollover code
Place this code container in the HEAD
:
<SCRIPT type="text/javascript">
<!--
if (document.images) {
var buttonOff = new Image(); // Inactive image ...
buttonOff.src = "blank.gif"; // .. here's its image
file
var buttonOn = new Image(); // Active
(mouseover) image
buttonOn.src = "active.gif"; // .. and _its_ image
file
}
function inact() { // For "inactive"
image
if (document.images) // Testing old browsers ...
document.images.button.src = buttonOff.src;
//
Switch to the "Off" image file
}
function act() { // For "active"
image
if (document.images) // Same as before ...
document.images.button.src = buttonOn.src;
//
Switch to the "On" image file
}
//
-->
</SCRIPT>
Now we need to change the IMG
tag as follows:
<P><A href="gadgets.html"
onMouseOver="
act()
"
onMouseOut="
inact()
"
>
<IMG src="images/blank.gif" height="30" width="30" name="button" align="middle"
border="0"></A> <strong>Rollo's Gadgets</strong></P>
Your rollover should work like this:
Rollo's Gadgets
Unlike your rollover, this example does not link to anything.
Congratulations! You have made your first image rollover. (If yours is not working, check your code carefully against the examples. The script alerts in Netscape (especially Netscape 6) and Internet Explorer may be helpful as well. If all else fails, send me email and paste your code into the message.)
Multiple rollovers
What if I have more than one rollover on a page? The script we just used won’t work in that case. We need to do three things:
- Create a pair of Image objects for each rollover and link them to the right image files.
- Change our
act()
andinact()
functions so they can accept arguments - that is, variable input. - Change our
IMG
tags so theonMouseOver
andonMouseOut
attributes pass along the image name as an argument.
JavaScript:Multiple rollovers on a single page
These functions are like the ones above, except that an argument called
imgName
has been introduced. As you’ll see,
this allows every rollover image on the page to use the same set of functions
(instead of requiring a separate function for every image).
<SCRIPT TYPE="text/javascript">
<!--
function inact(imgName) { // Note the argument imgName
if (document.images)
document.images[imgName].src // Gets the right
IMG
= eval(imgName + "n.src"); // Finds which Image to swap
}
function act(imgName) {
if (document.images)
document.images[imgName].src = = eval(imgName + "a.src");
}
//
-->
</SCRIPT>
This method depends on a consistent scheme for naming Image
objects. In this example, all “inactive” images end with the letter
n
and all “active” images end with an a
.
Building a rollover menu
Look at the following images. The left column contains “inactive” default images; the right contains “active” images.
![]() homen.gif |
![]() homea.gif |
![]() gadgetsn.gif |
![]() gadgetsa.gif |
![]() widgetsn.gif |
![]() widgetsa.gif |
![]() contactn.gif |
![]() contacta.gif |
I’ve given the “inactive” graphics names ending in n
and the “active” graphics names ending in a
. Using
a naming scheme like this helps avoid confusion. These images should already
be located in rollo/images; they are 124 pixels wide by 24 pixels
high.
- First let’s create eight
Image
objects for our fourIMG
elements. As with our image file names, “inactives” end inn
and “actives” end ina
. In index.html, replace the currentscript
container with the following:
- Now for some HTML. Try replacing the existing button images in index.html
with a stacked menu of the images in the left-hand column above (homen.gif,
gadgets.gif, widgetsn.gif, and contactn.gif).
- Have the first three images link to the pages you created. The fourth
one is an unadorned email link:
<a href="mailto:noname@noplace.com">
You’ll only need the elementsA
,IMG
, andBR
to build this menu. - Now add
onMouseOver
andonMouseOut
attributes to theA
tags. The argument should be the relevant image name, minus the finaln
ora
. For example, homea.gif and homen.gif will both use the argument home like this:
onMouseOver="
act('home')
"
onMouseOut="inact('home')
"
[Help! I’m lost!]
Put it all together and you should have a menu like this one:




Congratulations! You’ve mastered JavaScript rollovers.
https://www.angelfire.com/al4/rcollins/class/js/rollover.html