• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint

Including Random Content

Variety is the spice of life, and being able to add some random content allows you to add some variety to your Web pages. To do this, you first need to generate random numbers, and then use them to load random files or images.

In this example, we’ll have five different image files (Alice_4_1.jpg, Alice_4_2.jpg, Alice_4_3.jpg, Alice_4_4.jpg, and Alice_4_5jpg). We’ll generate random numbers and then use these numbers to fill in the last digit in the image’s file name.

1.
function randomRange(lowVal,highVal)
→ {...}

Add the function randomRange() to your JavaScript (Code 4.14). This is handled using the Math.random (generates a random decimal number) and Math.floor (rounds a decimal number to an integer) methods:

```Math.floor(Math.random() *
→ (highVal - lowVal + 1)) + lowVal;
```

Code 4.14. The function randomRange() generates a (pseudo) random number within the range specified. This can then be used to add random content to the page using JavaScript.

 Code View: Scroll / Show All``` DHTML & CSS Advanced | → Including Random Content ```

This will generate a random number between lowVal (the lowest value in the range) and highVal (the highest value in the range).

2.
document.write ('<img src="Alice_4_' +
→ randomRange(1,5) + '.jpg"/>');

To load an image randomly from the list, add a JavaScript document.write() that adds the image tag, replacing the numeral value in the filename with a random number between 1 and 5. When the page loads, a random image shows up (Figures 4.23, 4.24, 4.25, and 4.26).

Figure 4.26. The fourth time the page loads, one of the random images is repeated.

✓ Tips

• Actually JavaScript only allows you to generate pseudo-random numbers. These numbers are random, but if you know what the first number is, you can predict the subsequent numbers. This may not be good enough if you are trying to create an online casino, but will serve our purposes just fine.

• This example is relatively straightforward, but can be adapted for a wide variety of purposes. For example, you could combine it with the techniques discussed earlier in this chapter to randomly include an external JavaScript file or randomly load different files into iframes.

• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint