Chapter 16
Image-ine That!

 
In This Chapter

Among the modest delivery of new features that have arrived on the JavaScript 1.1 ship, image manipulation has been one of the more popular. This chapter explores the new Image object, which enables you to replace images on a Web page without reloading the entire page. In doing so, you can achieve several nice, although less-than-vital, page enhancements. Consider this chapter a handful of rainbow sprinkles (or “jimmies,” depending on your longitude) with which JavaScript 1.1 can add some extra bite to your Web pages.

Inside the Image Object

Traditional HTML coding allows you to place images at specified positions on a Web page—nothing new here. But what if you’d like to change one of the images on the page without loading a whole new HTML document? That’s the mission of JavaScript 1.1’s new Image object.

At its heart, the Image object provides a way for JavaScript code to change the source file of an image. Imagine, for instance, that you have a Web page that contains an image of a dog in the upper-left corner. Using the Image object and the right JavaScript code, you can change this dog image into, say, a cat image. The rest of the page remains unchanged.

Several applications of the Image object have become popular among JavaScript authors:

More experienced (read: jaded) Web authors may recognize that the above enhancements have been possible for some time, but they required more complicated programming methods. However, JavaScript 1.1 helps speed development for the experienced author and offers these enhancements even to novice Web programmers.

In this chapter, you’ll learn to use the Image object through an examination of two examples: the enhanced menu and the illustrated catalog. There are some good reasons why the animation application isn’t particularly wonderful; I’ll dish you that dirt towards the chapter’s close.

Let’s begin, though, with a look at creating an enhanced menu.

Glitz with Ease: Enhanced Menus

As simple and straightforward as text hyperlinks are, many Web designers prefer to add graphical menus to their pages. A common graphical menu, like the one shown here for instance, consists of a series of adjacent images. The user clicks one of these images, which presumably leads to some further activity.

A typical button menu, composed of several adjacent images.

Using JavaScript 1.1’s Image object, you can add some glitz to the above menu. Imagine that as the user passes his mouse pointer over each button, it becomes highlighted. In addition to adding aesthetic appeal, this also provides helpful feedback to the user, indicating which button is ready to respond to a click.

The enhanced button menu, which highlights each button as the mouse pointer passes over it. Note the change in border thickness and the minor spotlight effect on the selected button. Slick!

Before we get down and dirty with the enhanced menu JavaScript code, let’s talk specifics about the Image object.

Image Objectified

The Image object is similar to any other JavaScript object (which you learned about in Chapter 5, “Objects, Names, and Literals”). Thus, it has its own set of properties. As far as we’re concerned, the most important and effective property of the Image object is its source property, written as src, which you use to specify the image file you want to display, as in:

image.src = “kitty.jpg”

Picture a Web page that contains an image of a dog. The image has been specified in the HTML code in typical fashion:

<IMG SRC=”doggy.jpg” border=0 width=200 height=175>

There are two ways in which you can use the JavaScript Image object to alter the image that appears where the dog image currently resides on the page. You can reference the image by its index or by its name.

By Index 

The document object for the page contains an array known as images (also new to JavaScript 1.1). Each element of document.images[x] refers to an image on the page, in the order in which they were defined in the HTML code. For instance, in the page containing only the dog image, document.images[0] is the Image object that refers to it. If the page contained another image after the dog, its Image object would be document.images[1], and so forth.

Thus, to alter the image that appears in the dog’s place, you could change the order of the images in this way:

document.images[0].src = “kitty.jpg”

By Name

Often, you don’t include the NAME attribute in the <IMG> tag. However, you can do so, thereby giving the image an internal reference name:

<IMG name=dogimage SRC=”doggy.jpg” border=0 width=200 height=175>

Having done that, you can bypass the images array and refer to this Image object in JavaScript by its name:

document.dogimage.src = “kitty.jpg”

Naming Names

Important note: If the image is defined within a form, and you want to refer to it by name, you must specify
that form in the JavaScript expression, as in:

document.formname.dogimage.src = “kitty.jpg”

Ready to Code!

Now you’re ready to consider the code for your enhanced menu. Recalling how to use the src property of the Image object to change the image on a page, let’s walk through the logic of your proposed Web page and JavaScript program.

The Web page will be a mock clothing catalog. Its main page features a menu of four adjacent images: Help, Shirts, Hats, and Ties. Suppose you’ve saved these images as button1a.jpg, button2a.jpg, button3a.jpg, and button4a.jpg.

When designing these images in your image processing software, you also created “highlighted” versions of each image. Each highlighted version has a higher brightness level, a black border, and a spotlight effect (thanks to Adobe PhotoShop!). Suppose these highlighted images are saved as button1b.jpg, button2b.jpg, button3b.jpg, and button4.jpg.

Each of the menu images you’ve prepared for this page. No great artistic skill necessary!

Watch Your Dimensions!
Ideally, when using the JavaScript Image object to replace images on a page, the new image should possess the same physical dimensions as the original. If it does not, the Web browser will scale the new image to fit the dimensions of the image defined in the original <IMG> tag.

The JavaScript logic, then, goes as follows:

Simple enough? Basically, yes, although there is one trick to point out. MouseOver and MouseOut events cannot be triggered for standalone images. Rather, they apply only to hyperlinks and to defined areas in an image map (the latter of which is too complicated for this book). The trick: for each image, create a hyperlink that has no text and insert the <IMG> tag within the hyperlink definition. It might look like this:

<a href="help.htm" <img src="button1a.jpg" border="0" width="100" height="50"></a>

The above HTML code creates a hyperlink that consists only of the specified <IMG> and leads to “help.htm.” If you do not want the image to link anywhere, you can simply include a null href, as in:

<a href="" <img src="button1a.jpg" border="0" width="100" height="50"></a>

Using this trick, you can trigger MouseOver and MouseOut events when the mouse pointer passes over the image!

Taking that into account, the full HTML code for your page would look quite a bit like this:

<html>
<head>
<title>Kiwi Republic Clothing, Ltd., Inc., Corp.</title>
</head>
<body bgcolor="#FFFFFF">
<p><H2>Welcome to Kiwi Republic Clothing, Ltd., Inc, Corp.</H2></p><p>
<a href="help.htm" onMouseOut="unselect(1)" onMouseOver="select(1)">
<img src="button1a.jpg" border="0" width="100" height="50"></a>
<a href="shirts.htm" onMouseOut="unselect(2)" onMouseOver="select(2)">
<img src="button2a.JPG" border="0" width="100" height="50"></a>
<a href="hats.htm" onMouseOut="unselect(3)" onMouseOver="select(3)">
<img src="button3a.JPG" border="0" width="100" height="50"></a>
<a href="ties.htm" onMouseOut="unselect(4)" onMouseOver="select(4)">
<img src="button4a.JPG" border="0" width="100" height="50"></a>
</p>
<p>The Kiwi Republic has been serving important man with important fashions
for half a century. Now offering lines ranging from overpriced shirts to
overpriced neckties, we're proud to make our catalog available on the "Web".</p>
</body>
</html>

Function Fun

As illustrated above, you’ve created four images—each within a hyperlink definition—for each of button1a.jpg, button2a.jpg, and so on. As you might have noticed, you’ve also set two event handlers for each hyperlink: onMouseOut, which calls the JavaScript function unselect(), and onMouseOver, which calls select(). So now it’s time to code these two JavaScript functions!

First, unselect():

function unselect(butnum)
{ document.images[butnum-1].src = "button"+butnum+"a.jpg"}

Quite a compact little function, isn’t it?! This function takes one parameter, butnum, which specifies which button to change to the un-highlighted image. The function also contains a single line of code, which changes the image in question. And notice the document.images[x].src expression: In this case, x is butnum–1 because JavaScript considers the first image to be index zero (even if we humans prefer to call it button number one).

In the second half of the statement, you simply assign a string to the Image object, which represents the correct file name for the un-highlighted button, as in “button2a.jpg.”

Now for select():

function select(butnum)
{ document.images[butnum-1].src= "button"+butnum+"b.jpg"}

Hmm, sure looks familiar. In fact, select() is virtually the same function as unselect() except that it assigns the “b” file name to the Image object, as in “button2b.jpg.”

Thus, to change button one to its un-highlighted image, you simply need to call unselect(1). To highlight it, you call select(1). And that is exactly the logic behind this expression:

<a href="help.htm" onMouseOut="unselect(1)" onMouseOver="select(1)">
<img src="button1a.jpg" border="0" width="100" height="50"></a>

That’s all there is to it! You’ve created your images within hyperlinks, mixed in some event handlers, and added your JavaScript functions. Loading this page into your browser, you see the enhanced menus in glorious action.

When you slide the mouse pointer over an image, your JavaScript enhanced menu kicks in, replacing the plain image with a snazzy highlighted version.

For your reference, I’ve included the fully intact HTML code for this page, complete with the JavaScript functions described above.

<html>
<head>
<title>Kiwi Republic Clothing, Ltd., Inc., Corp.</title>
<script>
function unselect(butnum)
{ document.images[butnum-1].src = "button"+butnum+"a.jpg"}
function select(butnum)
{ document.images[butnum-1].src= "button"+butnum+"b.jpg"}
</script>
</head>
<body bgcolor="#FFFFFF">
<p><H2>Welcome to Kiwi Republic Clothing, Ltd., Inc, Corp.</H2></p><p>
<a href="help.htm" onMouseOut="unselect(1)" onMouseOver="select(1)">
<img src="button1a.jpg" border="0" width="100" height="50"></a>
<a href="shirts.htm" onMouseOut="unselect(2)" onMouseOver="select(2)">
<img src="button2a.JPG" border="0" width="100" height="50"></a>
<a href="hats.htm" onMouseOut="unselect(3)" onMouseOver="select(3)">
<img src="button3a.JPG" border="0" width="100" height="50"></a>
<a href="ties.htm" onMouseOut="unselect(4)" onMouseOver="select(4)">
<img src="button4a.JPG" border="0" width="100" height="50"></a>
</p>
<p>The Kiwi Republic has been serving important man with important fashions
for half a century. Now offering lines ranging from overpriced shirts to
overpriced neckties, we're proud to make our catalog available on the "Web".</p>
</body>
</html>

Slick: Illustrated Catalog

The Image object can also be used to change an image based upon user selection in a form. For instance, consider the Necktie Shopping page offered by Kiwi Republic, in which a selection box displays a list of available necktie styles. When the user selects any one style, its image appears on the right side of the page.

By and large, the basic concepts of this example remain unchanged from the enhanced menus. You begin your work by gathering the collection of necktie images to use. In this case, you’ve acquired five images, each of the same dimensions, with the file names tie0.jpg, tie1.jpg, tie2.jpg, and so on.

Next, you create the HTML code for the selection box form. Using this form, the user will select which tie to view.

<form name=tieform>
<select name="tiebox" size="5" onChange="ShowTie()">
<option selected>Plain Jane </option>
<option>Hearty Red </option>
<option>Green w/Envy </option>
<option>Power Blue </option>
<option>Crazy! </option>
</select>
<img name=tiephoto src="tie0.jpg" hspace="100" width="50" height="150"></p>
</form>

Pop-Up Image 

In the previous script, you created the form and named it tieform. You then defined the selection box with the name tiebox, and you specified each necktie option. Following the selection box definition, you placed the initial necktie image and named it tiephoto. Because Plain Jane is the initially selected item (<option selected>Plain Jane), tie0.jpg will be the initial image displayed.

Re-focusing on the selection definition tag, you see that an event handler is specified: onChange=”ShowTie()”. As a result, whenever the user changes the selected item, the JavaScript function ShowTie() is called. Let’s take a peek:

function ShowTie()
{
tieidx=document.tieform.tiebox.selectedIndex
document.tieform.tiephoto.src="tie"+tieidx+".jpg"
}

This is a mere two-statement function. In the first, you determine which item is currently selected. You do this by assigning the selectedIndex property of tiebox to the variable tieidx. Next, you use tieidx to construct the file name of the necktie image to assign to the src property of the tiephoto Image object. Making this assignment causes the tie image to change to reflect the currently selected item (see the following figure). Voila[ag]!

Capitalizing on the Image object, you change the necktime image that’s displayed to match the item selected in the form.

Here’s a complete rendition of the page’s code:

<html>
<head>
<title>Shopping for Neckties at the Kiwi Republic</title>
<script>
function ShowTie()
{
tieidx=document.tieform.tiebox.selectedIndex
document.tieform.tiephoto.src="tie"+tieidx+".jpg"
}
</script>
</head>
<body bgcolor="#FFFFFF">
<h2>Shopping for Neckties at the Kiwi Republic</h2>
<p>From the list below, select a necktie. An image of the tie appears to the right. If none of the 
neckties in our catalog suit your taste, there is something quite dubious about your tastes.</p>
<form name=tieform>
<select name="tiebox" size="5" onChange="ShowTie()">
<option selected>Plain Jane </option>
<option>Hearty Red </option>
<option>Green w/Envy </option>
<option>Power Blue </option>
<option>Crazy! </option>
</select>
<img name=tiephoto src="tie0.jpg" hspace="100" width="50" height="150"></p>
</form>
</body>
</html>

Future Projects

At the outset of this chapter, I implied that the Image object could be used to create animations. After having seen the Image object in action, you can probably imagine how an animation would be constructed:

It certainly works, but there are some real drawbacks. For one, the result isn’t much different from a typical animated GIF. What’s more, with an animated GIF, all the frames are stored in one file, which cause much less network delay than loading each individual image file does. 

On the other hand, if you create an animation using JavaScript code, you could program interactiveness that GIF animations lack. For instance, form buttons could be tied to a delay variable, which would speed up or slow down the rotation of image frames.

The Least You Need to Know

Previous Chapter Next Chapter


Beginning of ChapterTable of ContentsBook Home PageQue Home Page


For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.