- 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
Cycling Images with a Random Start
If you have a number of images that you want to display, you may not want to display them beginning with the same image each time the page is loaded. Script 4.20 has the HTML, and Script 4.21 combines the code used earlier for the cycling ad banners with the random image code.
Script 4.20. There’s a spacer GIF in the HTML file, which is a placeholder until the ad banner appears.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 → Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/ → xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Rotating Random Banner</title> <script type="text/javascript" → src="script11.js"></script> </head> <body bgcolor="#FFFFFF"> <div align="center"> <img src="images/spacer.gif" → width="400" height="75" id="adBanner" → alt="Ad Banner" /> </div> </body> </html>
Script 4.21. This script allows you to start your cycling image show with a random image.
window.onload = choosePic; var adImages = new Array("images/reading1.gif","images/reading2.gif","images/reading3.gif"); var thisAd = 0; function choosePic() { thisAd = Math.floor((Math.random() * adImages.length)); document.getElementById("adBanner").src = adImages[thisAd]; rotate(); } function rotate() { thisAd++; if (thisAd == adImages.length) { thisAd = 0; } document.getElementById("adBanner").src = adImages[thisAd]; setTimeout(rotate, 3 * 1000); }
To start images cycling from a random start:
var adImages = new Array("images/ → reading1.gif","images/reading2. → gif","images/reading3.gif");
As in previous examples, set up the array and the variable that contains the number of items in the array.
function choosePic() {
This function is similar to the choosePic() function in Script 4.19. See that explanation for the details of how it works.
function rotate() {
This function is similar to the rotate() function in Script 4.13. See that explanation for the details of how it works.