Previous Page
Next Page

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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Rotating Random Banner</title>
     <script src="script11.js"  language="javascript"  type="text/javascript"></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");

function rotate() {
      thisAd++;
      if (thisAd == adImages.length) {
         thisAd = 0;
      }
      document.getElementById("adBanner").src = adImages[thisAd];

      setTimeout("rotate()", 3 * 1000);

}

function choosePic() {
      thisAd = Math.floor((Math.random() * adImages.length));
      document.getElementById("adBanner").src = adImages[thisAd];

      rotate();
}

To start images cycling from a random start:

1.
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.

2.
function rotate() {



This function is the same as the rotate() function in Script 4.13. See that explanation for the details of how it works.

3.
function choosePic() {



This function is the same as the choosePic() function in Script 4.19. See that explanation for the details of how it works.


Previous Page
Next Page