Java Reference
In-Depth Information
the page is found in the element
document.images[0]
, the second in
document.images[1]
, and
so on.
If you want to, you can assign a variable to reference an
img
object in the
images
collection. It can
make code easier to type and read. For example, the following code assigns a reference to the
img
object at index position
1
to the
myImage2
variable:
var myImage2 = document.images[1];
Now you can write
myImage2
instead of
document.images[1]
in your code, with exactly the same effect.
Because the
document.images
property is a collection, it has properties similar to the native
JavaScript
Array
type, such as the
length
property. For example, if you want to know how many
images are on the page, the code
document.images.length
will tell you.
trY it out
Image Selection
The
img
object itself has a number of useful properties. The most important of these is its
src
property.
By changing this, you can change the image that's loaded. This example demonstrates this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 8, Example 3</title>
</head>
<body>
<img src="" width="200" height="150" alt="My Image" />
<script>
var myImages = [
"usa.gif",
"canada.gif",
"jamaica.gif",
"mexico.gif"
];
var imgIndex = prompt("Enter a number from 0 to 3", "");
document.images[0].src = myImages[imgIndex];
</script>
</body>
</html>
Save this as
ch8_example3.html
. You will also need four image files, called
usa.gif
,
canada.gif
,
jamaica.gif
, and
mexico.gif
. You can create these images yourself or obtain the ones provided with
the code download for the topic.
A prompt box asks you to enter a number from
0
to
3
when this page loads into the browser. A
different image is displayed depending on the number you enter.
At the top of the page you have your HTML
<img/>
element. Notice that the
src
attribute is left empty:
<img src="" width="200" height="150" alt="My Image" />