Prev | Current Page 214 | Next

Craig Grannell

"The Essential Guide to CSS and HTML Web Design"


document.getElementById('randomImage').setAttribute
??('src','assets/random-images/'+chosenImage[getRan]);
6. Add JavaScript to set the alt text. Setting the alt text works in a similar way to step
5, but the line is slightly simpler, due to the lack of a path value for the alt text:
document.getElementById('randomImage').setAttribute
??('alt',chosenAltCopy[getRan]);
7. Style the image. In CSS, add the following two rules. The first removes borders by
default from images that are links. The second defines a border for the image
added in step 1, which has an id value of randomImage.
a img {
border: 0;
}
#randomImage {
border: solid 1px #000000;
}
Upon testing the completed files in a browser, each refresh should show a random image
from the selection, as shown in the following screenshot. (Note that in this image, the
padding value for body was set to 20px 0 0 20px, to avoid the random image hugging the
top left of the browser window.)
WORKING WITH IMAGES
141
4
There are a couple of things to note regarding the script. To add further images/alt text,
copy the previous items in each array, increment the number in square brackets by one
and then amend the values??”for example:
var chosenImage=new Array();
chosenImage[0]="stream.jpg";
chosenImage[1]="river.jpg";
chosenImage[2]="road.jpg";
chosenImage[3]="harbor.jpg";
var chosenAltCopy=new Array();
chosenAltCopy[0]="A stream in Iceland";
chosenAltCopy[1]="A river in Skaftafell, Iceland";
chosenAltCopy[2]="A near-deserted road in Iceland";
chosenAltCopy[3]="The harbor in Reykjav?­k ";
You??™ll also note that in this example, the height and widths of the images is identical.


Pages:
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226