For
the former, only the image file names are needed??”not the path to them (that will
be added later). Note that the order of the items in the arrays must match??”in
other words, the text in the first item of the chosenAltCopy array should be for the
first image in the chosenImage array.
var chosenImage=new Array();
chosenImage[0]="stream.jpg";
chosenImage[1]="river.jpg";
chosenImage[2]="road.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";
3. Create a random value. The following JavaScript provides a random value:
var getRan=Math.floor(Math.random()*chosenImage.length);
4. Create a function. Add the following text to start writing the JavaScript function,
which was earlier dubbed randomImage (see step 1??™s onload value). If you??™re not
familiar with JavaScript, then note that content from subsequent steps must be
inserted into the space between the curly brackets.
function randomImage()
{
}
Creating a JavaScript-based image randomizer
THE ESSENTIAL GUIDE TO CSS AND HTML WEB DESIGN
140
5. Add JavaScript to set the image. By manipulating the Document Object Model
(DOM), we can assign values to an element via its id value. Here, the line states to
set the src attribute value of the element with the id value randomImage (i.e., the
image added in step 1) to the stated path value plus a random item from the
chosenImage array (as defined via getRan, a variable created in step 3).
Pages:
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225