- Creating Rollovers
- Creating More Effective Rollovers
- Building Three-State Rollovers
- Triggering Rollovers from a Link
- Making Multiple Links Change a Single Rollover
- Working with Multiple Rollovers
- Creating Cycling Banners
- Adding Links to Cycling Banners
- Building Wraparound Slideshows
- Displaying a Random Image
- Cycling Images with a Random Start
Displaying a Random Image
If your site is rich with graphics, or if you are displaying digital artwork, then you may want to have a random image from your collection appear when the user enters your site. Once again, JavaScript to the rescue! The extremely simple Listing 4.20 shows the required HTML, and Listing 4.21 provides the JavaScript. shows the result of the script, in this case images of a stuffed lion, tiger, and bear (oh, my!).
To display a random image:
- var myPix = new Array("images/lion.jpg", "images/tiger.jpg", "images/bear.jpg");
Inside the function choosePic(), as is now familiar, build an array of three images, and stuff it into the variable myPix.
- randomNum = Math.floor((Math.random() * myPix.length));
The variable called randomNum gets the value of a math expression that’s best read from the inside outwards. Math.random generates a random number between 0 and 1, which is then multiplied by myPix.length, which is the number of items in the array (in this case, it’s 3). Math.floor rounds the result down to an integer, which means that the number must be between 0 and 2.
- document.getElementById("myPicture").src = myPix[randomNum];
This says that the source of the image myPicture is set based on the array myPix, and the value at this moment is dependent on the value of randomNum.
Listing 4.20. This simple HTML creates the page for a random image.
<!DOCTYPE html> <html> <head> <title>Random Image</title> <script src="script10.js"></script> <link rel="stylesheet" href="script01.css"> </head> <body> <img src="images/spacer.gif" width="305" height="312" id="myPicture" alt="some image"> </body> </html>
Listing 4.21. You can display random images on your page with this script, which uses JavaScript’s Math.random method to generate a random number.
window.onload = choosePic; function choosePic() {
var myPix = new Array("images/lion.jpg", "images/tiger.jpg","images/bear.jpg");
var randomNum = Math.floor ((Math.random() * myPix.length));
document.getElementById("myPicture").src = myPix[randomNum];
}