HTML and CSS Reference
In-Depth Information
EXAMPLE
12.6
<html>
<head><title>Preloading Images</title>
<script type="text/javascript">
1
function preLoadImages()
{
2
baby = new Array(); //
global variable
3
baby[0]=new Image();
4
baby[0].src="baby1.jpg";
baby[1]=new Image();
// Preload an image
5
baby[1].src="baby2.jpg";
}
</script>
</head>
6 <body bgcolor="cornflowerblue"
onLoad="preLoadImages()
;">
<h2>This Is Baby William</h2>
7
<a href="#" onMouseOver="document.willy.src=baby[1].src
;"
8
onMouseOut="document.willy.src=baby[0].src;">
9 <img name="willy" src="baby1.jpg" width=190 height=200 />
</a>
</body>
</html>
EXPLANATION
1
A function called
preLoadImages()
is defined in the head of the document. It will
define a list of images that will be loaded before anything else. With this technique
(unless the images are large or great in number), the viewer will have the neces-
sary images in his browser's cache before the script starts to run, reducing waiting
time. For a small example, such as this, there will be no noticeable difference.
2
The new array, called
baby
, is declared.
3
The
Image()
constructor creates and preloads a new
image
object and assigns it to
the first element of the
baby
array.
4
The
src
property is assigned the name of the external image file called
baby1.jpg
.
5
The
src
property is assigned the name of the external image file called
baby2.jpg
.
6
When the page has loaded, the
onLoad
event is triggered causing the
preLoadIm-
ages()
function to be called.
7
The # (hash mark) disables the link so that the browser does not try to go to a URL
when clicked. The link is an image. The
onMouseOver
event is triggered when the us-
er's mouse moves onto the link, and the
onMouseOut
event is triggered when the user's
mouse moves away from the link (image). When the mouse moves over the image,
the baby image changes from the first image to the second one. When the mouse is
moved away from the image, the original image is displayed. Going down the Java-
Script hierarchy, we start with the
document
, then to
document.willy
or
document.im-
ages[0]
or
document.images[“willy”]
), then to the
src
property that is assigned the
im-
age
object. One image is replaced with another. Note:
document.images[“willy”]
is an
associative array. Any object, not just the
Array
object, can use the square bracket no-
tation to reference its properties. See Chapter 9, “JavaScript Core Objects.”
Continues