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. 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>
     <title>Rotating Random Banner</title>
     <script src="script11.js"></script>
     <link rel="stylesheet" href="script01.css">
     <div class="centered">
        <img src="images/spacer.gif" id="adBanner" alt="Ad Banner">

Listing 4.23. 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 Listing 4.21. See that explanation for the details of how it works.

  3. function rotate() {

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

  • + Share This
  • 🔖 Save To Your Account