HTML and CSS Reference
In-Depth Information
EXAMPLE
12.5 (
CONTINUED
)
<h2> This Is Baby William</h2>
1
<img name="display" src="baby1.jpg" width="220" height="250" >
<script type="text/javascript">
2
var myImages=new Array("baby1.jpg", "baby2.jpg",
"baby3.jpg");
3
var n = prompt("Pick a number between 1 and 3","");
4
n--;
5
document.images["display"].src = myImages[n];
//
document.images[0].src = myImages[n]
</script>
</body>
</html>
EXPLANATION
1
An HTML inline image called
display
is created. Its source is a file called
baby1.jpg
with the width and height defined in pixels.
2
An array object called
myImages
is created with the
Array()
constructor. The ele-
ments of the array are three
.jpg
files.
3
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
.
4
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.
5
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).