254
Part III Integrating JavaScript into Design
Figure 13-1 The initial load of the box1.png graphic through a webpage.
When you move the mouse over the graphic, the mouseover event fires, and the following
code changes the source of the graphic to box2.png:
window.document.img_home.src='box2.png'
While the mouse is over the graphic, the image changes to the one shown in Figure 13-2, in
which the direction of the gradient is reversed.
Figure 13-2 The graphic changes when the mouse moves over it.
Chapter 13 Working with Images in JavaScript
255
When the mouse moves away from the graphic, the image changes back to box1.png, thanks
to the mouseout event, which calls this JavaScript:
window.document.img_home.src='box1.png'
Modern Rollovers
A newer method for creating rollovers with JavaScript is to use the Document Object Model
(DOM) and the onload event of the window object. (The onload event of the window object
was covered in Chapter 11, “JavaScript Events and the Browser.”) With the DOM in use, when
the page calls the onload event, the onload handler calls a JavaScript function that populates
the mouseover and mouseout events for all the images in the document.
Using Modern Rollovers
Although I call using the DOM with onload “Modern Rollovers,” and it does accomplish the goal of unobtrusive scripting, it can be somewhat cumbersome. It can also
be slightly less compatible when used across various browsers and platforms.
The pragmatist in me wants to say that using the example that was just shown is acceptable, especially if your webpage has just a few graphics, but I feel like I’m teaching a
bad practice if I tell you to use it. Therefore, I leave it up to you to choose which approach
works best for you. If you have a lot of graphics that require the rollover effect, you’ll
find that this second, more current approach, which uses a generic function to handle
the rollover events, is easier to maintain.
This page works exactly the same as the example in the preceding section, but uses different
code, as shown in Listing 13-1 (see listing13-1.txt in the sample code).
Listing 13-1 A different approach to rollovers
function rollover() {
var images = document.getElementsByTagName("img");
var imgLength = images.length;
for (var i = 0; i < imgLength; i++) {
images[i].mouseover = mouseOver;
images[i].mouseout = mouseOut;
}
}
function mouseOver() {
this.src = "box2.png";
}
function mouseOut() {
this.src = "box1.png";
}
256
Part III Integrating JavaScript into Design
This code, coupled with an onload event handler, creates a simple mouseover effect. By using
the EHandler event creation object with the code created in Chapter 11 (ehandler.js), you can
add the onload event to the
tag. First, include the ehandler.js script:
Next, the rollover function gets called in response to the onload event. Again, you set this up
using the EHandler object's add method. Add the following code to the end of the HTML:
Even though the functionality is the same as the preceding example, the code in Listing 13-1
is not very portable. (You do some work to improve that soon.) Following is an explanation of
the code from Listing 13-1.
The function retrieves all the
![]()
elements using the getElementsByTagName() method of
the document object, and places them into a variable called images. Next, the code retrieves
the number of elements contained in the images variable by using the length property, and
stores the result in the imgLength variable. The code uses the value in imgLength to iterate
through all the images. Within the loop, it sets the mouseover and mouseout events to their
respective functions, called mouseOver() and mouseOut() in this code.
Up to this point, the code is remarkably portable, though it doesn’t reflect best practice. The
code gets a bit worse within the mouseOver and mouseOut event handlers, because the src
attributes are hard-coded to the file names box1.png and box2.png. This is fine if all you
have is one image and its accompanying rollover, as in this example. However, if you have a
page full of images, as is more likely the case in the real world, this code breaks. In addition,
the this keyword is quirky when it is called from another function related to event handling.
Therefore, the script needs improving.
This example code does show the basic theory of how to implement rollovers. Loop through
the images (or retrieve them by ID) and set their mouseover and mouseout events to specific
functions, which in turn should set the src attribute to the name of the image to use for that
event. Now it’s your turn to make the function more portable so that you can use it in the
future.
This exercise uses six images (three graphics, each of which has a default and a rollover image), but the code is written to support any number of images. I included the images used
in this exercise with the downloadable code for this book, so you don’t have to reinvent the
wheel just to make this exercise work.
Chapter 13 Working with Images in JavaScript
257
Creating portable rollovers
1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file rollover.htm in the
Chapter13\rollover sample files folder in the companion content. This folder includes
six images: home_default.png, home_over.png, about_default.png, about_over.png,
blog_default.png, and blog_over.png. The file names containing _default are the images
to display initially; the file names containing _over are the rollover images.
2. Within the webpage, add the boldface code shown here into rollover.txt (to replace the
TODO comments):
"http://www.w3.org/TR/html4/strict.dtd">
Rollover


3. View the page in a browser. You should see a page similar to this screenshot. If you run
into problems, make sure that each of the images is located in the current directory,
because that’s where the
![]()
tag is looking for them.
258
Part III Integrating JavaScript into Design
4. Roll the mouse over the buttons one at a time. Each image should change to its corresponding rollover image. Here’s what the screen looks like when the mouse is over the
Blog graphic:
This example shows a better rollover implementation. Like the previous example, this code
creates a function and then calls it using the window.onload event. Also, like the previous example, this code gathers all the images into a variable called images and then loops through
each one, adding an mouseover and mouseout event handler to each, as follows:
Chapter 13 Working with Images in JavaScript
259
function rollover() {
var images = document.getElementsByTagName("img");
var imgLength = images.length;
for (var i = 0; i < imgLength; i++) {
EHandler.add(images[i],"mouseover", function(i) {
return function() {
images[i].src = images[i].id + "_over.png";
};
}(i));
EHandler.add(images[i],"mouseout", function(i) {
return function() {
images[i].src = images[i].id + "_default.png";
};
}(i));
}
}
Again, the example uses the EHandler event registration script developed in Chapter 11,
calling the EHandler add() method to register a mouseover and mouseout event set for each
image. The function used to register events is somewhat complex because of a problem with
how Windows Internet Explorer handles the keyword this in event handling.
In other browsers such as Firefox, the this keyword refers to the actual element where the
event fires—in this case, the img element. However, Internet Explorer doesn't register an
event until it's used, so the element isn't registered during the event registration (inside of
the for loop). Therefore, the code needs to jump through some hoops to pass a reference to
the element for Internet Explorer. In this case, the index i is passed into the wrapper function,
which then calls its own anonymous function.
This example differs from Listing 13-1 because it removes the definitions of the mouseOver()
and mouseOut() functions. With this example, each image’s ID is gathered with a call to
images[i].id within an anonymous function. That name is then concatenated with the string
“_over.png” and “_default.png” for their respective functions.
Making sure that the file names and the
![]()
tags’ id attributes match is important. For
example, here’s one of the
![]()
tags from the example:

Because these file names are generated in the mouseover and mouseout event handlers
based on the element IDs, the file names for the About graphic must be about_default.png
and about_over.png. Similarly, the image file names must be home_default.png and home_
over.png for the Home graphic, and so on.
260
Part III Integrating JavaScript into Design
Note Of course, you could use an entirely different naming convention—the important issue is
that the naming convention you use for the rollover graphics files must match what you coded in
the JavaScript.
The rollover() function shown in the example gathers all the images on the page. For realworld pages, that means there’s a good chance that the images variable list contains graphics
and images that don’t have a rollover action. Therefore, a further improvement on this script
is to create a conditional to check whether the graphic should be a rollover. One of the simplest solutions is to refine the naming convention for rollover graphics to include the word
rollover in the
![]()
tag’s id attribute, like this:

The new code iteration uses a regular expression through the match() method to examine
whether the id attribute contains the word rollover. If it does, the code continues the rollover
action; otherwise, it simply returns. Figure 13-3 shows an example page with four images,
three of which have rollover behavior.
Figure 13-3 An example with only certain images being rollovers.
When you move the mouse over any of the top three images on the page, the rollover image
loads. However, because the ID of the last image doesn’t contain the word rollover, it doesn’t
get a mouseover or mouseout event handler. Here’s the full code (but note that the script still
needs a little more improvement before it’s done). Note the new names of the image files.
(This code is included in the companion content sample files in the \rolloverregexp folder.)
Chapter 13 Working with Images in JavaScript
261
"http://www.w3.org/TR/html4/strict.dtd">
Rollover
alt="Home">

alt="Blog">

alt="About">

The differences between this code and the earlier code are slight and exist within the rollover() function and the img elements in the HTML. In the rollover() function, a regular expression is built directly within the match() method to look for the string rollover within the
image’s id attribute. If the string rollover appears within the ID, the rollover action is set, just
as in the previous examples. If the string isn’t found, the for loop continues.
262
Part III Integrating JavaScript into Design
Preloading Images
You may have noticed an issue when you first began working with the rollover examples in
the previous section. When the rollover image is first loaded, it can take a second to render.
This delay occurs because the image has to be loaded through the web server and network
before it is displayed in the browser.
This isn’t a huge issue; it’s more of an annoyance when using the application across a super
fast network connection. However, the lag is noticeable in real-world web applications, especially for users who may be running on slow dial-up connections. Luckily, you can preload the
images using a little JavaScript. Preloading stores the images in the browser’s cache, so they
are available almost instantly when a visitor moves the mouse over an image.
The basic premise behind preloading an image is to create an image object and then call the
src() method on that object, pointing to the image you’d like to preload. What you do with
that object after you call the src() method isn’t important. JavaScript makes the call to load
the image asynchronously, so the rest of the script continues to execute while the image
loads in the background.
The asynchronous nature of preloading does have an important implication when you’re
working with multiple images: you must create a new image object for each image that you
need to preload. If you have a batch of rollover images, as is often the case, each image
needs its own object and src() method call.
The final version of the rollover code incorporates preloading. Listing 13-2 shows the rollover
script as well as the HTML page for context; the preload elements of the code are shown in
boldface. This code is included in the companion content sample files in the rollover \regexppreload folder.
Listing 13-2 Preloading and rollovers.
Rollover
alt="Home">

alt="About">

alt="Blog">

To review, the code uses the image tag naming convention to construct the image names,
so all the same warnings about synchronizing the id attributes with your JavaScript code discussed earlier in this chapter apply.
Working with Slideshows
You can use JavaScript to create a “slideshow” effect in which one image is swapped for another in the browser window. For the purposes of this chapter, you build a visitor-controlled
slideshow—that is, one in which the visitor controls the image changes by clicking buttons to
move forward and backward through them, as opposed to the timed slideshow, in which the
application swaps the images automatically after a certain interval.
Creating a Slideshow
You can implement slideshow functionality through JavaScript in several ways. One approach
might be to use a for loop to iterate through the images, but this section illustrates another,
more straightforward slideshow variation.
264
Part III Integrating JavaScript into Design
Most slideshows are rather simple in design, though admittedly I’ve seen some overly complex ones. Listing 13-3, which I explain, shows the slideshow in its first version, with just forward capability.
Listing 13-3 A basic (but slightly incomplete) slideshow.
"http://www.w3.org/TR/html4/strict.dtd">
Slideshow
I might as well discuss the HTML portion of this code, because it’s short. Here it is:
