Java Reference
In-Depth Information
The images Collection
As you know, you can insert an image into an HTML page using the following tag:
<img alt=”USA” name=”myImage” src=”usa.gif” />
The browser makes this image available for you to manipulate with JavaScript by creating an img object
for it with the name myImage. In fact, each image on your page has an img object created for it.
Each of the img objects in a page is stored in the images collection, which is a property of the document
object. You use this, and other collections, as you would an array. The fi rst image on 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 read. For example, the following code assigns a reference to the img object at index posi-
tion 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.
You can also access img objects in the images collection by name. For example, the img object created
by the <img/> element, which has the name myImage, can be accessed in the document object's images
collection property like this:
document.images[“myImage”]
Because the document.images property is a collection, it has the properties similar to the native
JavaScript Array type, such as the length property. For example, if you want to know how many
images there 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. The next example demonstrates this.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 6: Example 3</title>
</head>
<body>
<img name=”img1” src=”” border=”0” width=”200” height=”150” />
<script type=”text/javaScript”>
var myImages = new Array(“usa.gif”,”canada.gif”,”jamaica.gif”,”mexico.gif”);
var imgIndex = prompt(“Enter a number from 0 to 3”,””);
document.images[“img1”].src = myImages[imgIndex];
</script>
</body>
</html>
Search WWH ::




Custom Search