HTML and CSS Reference
EXAMPLE 12.5 ( CONTINUED )
<h2> This Is Baby William</h2>
<img name="display" src="baby1.jpg" width="220" height="250" >
var myImages=new Array("baby1.jpg", "baby2.jpg",
var n = prompt("Pick a number between 1 and 3","");
document.images["display"].src = myImages[n];
// document.images.src = myImages[n]
An HTML inline image called display is created. Its source is a file called baby1.jpg
with the width and height defined in pixels.
An array object called myImages is created with the Array() constructor. The ele-
ments of the array are three .jpg files.
The user is prompted to pick a number between 1 and 3, which will determine
which image will be displayed. The user input is assigned to variable n .
Array indexes start at 0. The user entered a number between 1 and 3, and because
n will be used as an index into the array, it must be decremented to produce an
index number ranging from 0 to 2.
The images array can be indexed by number or name. In this example, display is
the name given to the default image shown on the screen, baby.jpg . By changing
the src property, the default image will be replaced by any one of the images listed
in the myImages array. See Figure 12.12.
Figure 12.12 Another example of image replacement: Output from Example 12.5 (left)
after the user picks a number (right).