- 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. Listing 4.22 has the HTML, and Listing 4.23 combines the code used earlier for the cycling ad banners with the random image code.
Listing 4.22 There’s a spacer GIF in the HTML file, which is a placeholder until the ad banner appears.
<!DOCTYPE html> <html> <head> <title>Cycling Random Banner</title> <script src="script11.js"></script> <link rel="stylesheet" href="script01.css"> </head> <body> <div class="centered"> <img src="images/spacer.gif" id="adBanner" alt="Ad Banner"> </div> </body> </html>
Listing 4.23 This script allows you to start your cycling image show with a random image.
window.onload = choosePic; var theAd = 0;var adImages = new Array("images/reading1.gif","images/reading2.gif","images/reading3.gif");
function choosePic() { theAd = Math.floor(Math.random() * adImages.length); document.getElementById("adBanner").src = adImages[theAd]; rotate(); }function rotate() {
theAd++; if (theAd == adImages.length) { theAd = 0; } document.getElementById("adBanner").src = adImages[theAd]; 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 rotate() {
This function is similar to the rotate() function in Listing 4.15. See that explanation for the details of how it works.