Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

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.

→ Transitional//EN"
        → xhtml1-transitional.dtd">
<html xmlns="">
     <title>Rotating Random Banner</title>
     <script type="text/javascript"
     → src="script11.js"></script>
<body bgcolor="#FFFFFF">
     <div align="center">
        <img src="images/spacer.gif"
        → width="400" height="75" id="adBanner"
        → alt="Ad Banner" />

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];


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

     setTimeout(rotate, 3 * 1000);

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 choosePic() {

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

  3. function rotate() {

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

  • + Share This
  • 🔖 Save To Your Account