When called, the function will cause the next image in the array to be displayed.. 6 The name of the image, babypic, is used as an index into the images[] array to refer-ence the defaul
Trang 1By changing the value assigned to the src property of an image, it is possible to
dynam-ically replace one image with another You can create an array of images with the Array()
constructor, and assign any one of these images to the src property of the JavaScript
images[] array
E X A M P L E 1 2 4
<html>
<head><title>HTML Images</title>
<script type="text/javascript">
1 var myImages=new Array("baby1.jpg", "baby2.jpg",
"baby3.jpg", "baby4.jpg");
5 if (index_val < myImages.length){
6 document.images["babypic"].src = myImages[index_val];
// could say document.babypic.src or // document.images[0].src
}
index_val=0;
document.images["babypic"].src = myImages[index_val];
} }
8 function previous_image(){
index_val ;
9 if (index_val >= 0){
document.images["babypic"].src = myImages[index_val];
}
index_val=myImages.length - 1;
document.images["babypic"].src = myImages[index_val];
} }
</script>
</head>
<body>
<div align="center">
<h2>Baby Gallery</h2>
11 <img name="babypic" id="babypic" src="baby1.jpg"
width="329" height="440" >
<br />
Trang 212 <a href="JavaScript:next_image()">
View next baby<br />
</a>
13 <a href="JavaScript:previous_image()">
View previous baby<br />
</a>
</div>
</body>
</html>
E X P L A N A T I O N
1 The array myImages consisting of four images is created by the Array() constructor.
2 The index value for the array is assigned to a variable called index_val.
3 A function called next_image() is defined When called, the function will cause
the next image in the array to be displayed
4 By increasing the value of the index, the next image in the array will be accessed
5 As long as the end of the array hasn’t been reached, the block will be entered and
the new image displayed
6 The name of the image, babypic, is used as an index into the images[] array to
refer-ence the default image by name By assigning a new image (from the myImages
ar-ray) to the image’s src property, the current image will be replaced by the new image.
7 If the end of the array has been reached, the statements within the else block will
be executed, resetting the array index back to the beginning, index 0
8 A function called previous_image() is defined When called, it will go backward in
the array and cause the previous image to be displayed
9 If the index value is still ≥0, we are still within the boundaries of the array
10 If by subtracting one from the index value, we have ended up with a value of –1,
we are out of the bounds of the array, and will set the index value back to the size
of the array, its length –1
11 This is the initial image displayed on the screen before the user initiates an action
12 When this link is clicked, the JavaScript function called next_image() is invoked.
13 When this link is clicked, the JavaScript function called previous_image() is invoked.
See Figure 12.11
E X A M P L E 1 2 4 (C O N T I N U E D)
Trang 3Figure 12.11 Image replacement Each time a link is pressed, one image is replaced with
another.
E X A M P L E 1 2 5
<html>
<head><title>HTML Replacing Images</title></head>
<body bgcolor="cornflowerblue">
Trang 4<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","");
5 document.images["display"].src = myImages[n];
// document.images[0].src = myImages[n]
</script>
</body>
</html>
E X P L A N A T I O N
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.
E X A M P L E 1 2 5 (C O N T I N U E D)
Trang 5If you assign a new image to the src property of an image object, there might be some lag
in the time it takes to download the image from the server And if you have a slow
con-nection, this can be a real turnoff, to the point that you don’t even bother to wait for the
image to load To solve this problem, the Image() constructor allows you to preload an
offline image; this puts the image in the browser’s cache before it is used This technique
of caching the image makes the response time much faster, especially when you have
large images, animation, rollovers, and the like The Image() constructor can also define
the size (height and width, in pixels) of the cached image Be sure to put the Image()
constructor in the <head> portion of the document so that the images are put in the
cache before the script starts to run For seamless transition when replacing one image
with another, both images should be of the same size, accomplished by cropping or
scal-ing the image To use the Image() constructor, see next.
It is possible, but unlikely, the viewer is using a browser that doesn’t support the
image object We can add a little snippet of code to detect if the image object exists and
then continue with preloading the images:
if(document.images){
pic1=new Image(100,25);
pic1.src="http://someplace.com/image1.gif";
}
A Simple Rollover with a Mouse Event. We talked about event handlers with the
form object and now we will demonstrate the use of an event handler with the image
object For a complete discussion, see Chapter 13 The objective of the next example is
to change the image when the mouse rolls over a link, and to change it back when the
mouse moves away from the link There are two images involved: the image that initially
appears on the page and the image that replaces it when the mouse rolls over the link
associated with it Both of the images are preloaded with the Image() constructor The
JavaScript onMouseOver event is triggered when the user’s mouse moves onto the link,
and the onMouseOut event is triggered when the mouse moves away from the link
F O RM A T
var newImage = new Image();
var newImage = new Image(height, width)
newImage.src = "image.gif";
E X A M P L E
var myImage = new Image(200,300);
myImage.src = "baby.gif";
Trang 6E X A M P L E 1 2 6
<html>
<head><title>Preloading Images</title>
<script type="text/javascript">
1 function preLoadImages(){
2 baby = new Array(); // global variable
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>
E X P L A N A T I O N
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 usus-er’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.ages[0] or document.images[“willy”]), then to the src property that is assigned the
im-age object One imim-age is replaced with another Note: document.imim-ages[“willy”] is an
associative array Any object, not just the Array object, can use the square bracket
Trang 712.3.3 Randomly Displaying Images and the onClick Event
By using the Math object’s random() method, it is sometimes fun to randomly generate
pictures from a list of images Example 12.7 demonstrates how to change the src
attri-bute of an image object by using a random number as the index of an element in an
image array All of the images are preloaded by using the Image() constructor, greatly
improving the time it takes to load the images
8 When the mouse is moved away from the link, the initial image baby1.jpg will
re-appear on the screen
9 The initial external image called baby1.jpg is named willy and is aligned on the left
side of the screen The output is shown in Figure 12.13
Figure 12.13 Before the mouse rolls over the image (left), as the mouse hovers over
the image (middle), and when the mouse moves away from the image (right).
E X A M P L E 1 2 7
<html>
<head><title>Preloading Images</title></head>
<script type="text/javascript">
2 for(var i=0; i<3; i++){
ImageHome[i]=new Image();
}
3 ImageHome[0].src="baby1.jpg";
ImageHome[1].src="baby2.jpg";
ImageHome[2].src="baby3.jpg";
6 var randnum=Math.floor(Math.random() * (n + 1));
7 document.images["display"].src = ImageHome[randnum].src;
}
</script>