Arrays of Pictures
Why put pictures in an array?
Mechanics:
Let's say you have ten pictures all in the same directory somewhere.:
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
| r/r1.jpg | r/r2.jpg | r/r3.jpg | r/r4.jpg | r/r5.jpg | r/r6.jpg | r/r7.jpg | r/r8.jpg | r/r9.jpg | r/r10.jpg |
Images excerpted from Webster's New International Dictionary of the English Language, 1911.
To load the images in an array involves work such as the following:
| JavaScript | description |
pix=new Array(10); |
create a new array of ten elements. |
pix[0]=new Image; pix[0].src="r/r1.jpg"; pix[1]=new Image; pix[1].src="r/r2.jpg"; pix[2]=new Image; pix[2].src="r/r3.jpg"; . . . pix[9]=new Image; pix[9].src="r/r10.jpg"; |
let each element of the array be an Image object with source defined by a string that refers to a file containing a picture. |
If the files containing the 10 images are named with consecutive numbers, then we may streamline the process through a loop:
| JavaScript | description |
pix=new Array(10); |
create a new array of ten elements. |
for (i=0;i<10;i++){
pix[i]=new Image;
pix[i].src="r/r"+(i+1)+".jpg";
}
|
let each element of the array be an Image object with source defined by a string that refers to a file containing a picture. |
The above "selection" object is driven quite simply by:
<select name="u" size="3" onchange="p.src=pix[u.value-1].src"> ... <img src="p1.jpg" name="p">