Lab 5—Your First JavaScripts

Part 2—Make your images rotate


The JavaScript you add now will cause your images to rotate. First, one will appear, then the next, then the next, causing a sensation of movement. The four images will cycle through and then repeat endlessly.

  1. Open lab05.html in NotePad++.
  2. Save the file as banner.html.
  3. Change the title to "Banner by " and your name; for example, "Banner by Joy".
  4. In the body, insert an image tag for the first of your four images. Give it an id of Banner.
    <img src="pic1.jpg" alt="Banner" id="Banner" />


  5. In the head, after the title, add a header script:

    <script type="text/javascript">
        window.onload = rotate;

        var myImages = new Array("pic1.jpg","pic2.jpg","pic3.jpg","pic4.jpg");
        var thisImage = 0;

        function rotate()
        {
            thisImage++;
            if (thisImage == myImages.length)
            {
                thisImage = 0;
            }
            document.getElementById("Banner").src =             myImages[thisImage];
            setTimeout("rotate()", 3 * 1000);
        }
    </script>

  6. Save banner.html again.
  7. Open banner.html in Firefox. Does the banner change images every 3 seconds. If you want it to change faster or slower, change the value in setTimeout from 3 to something else.

    If it's not working, use the Firefox Error Console to help you find and fix your errors.

 

You're finished with your banner!

The next page will explain what to submit for lab 5

previous page   next page

 

Explanation of HTML

  1. By giving the image an id, we can access its source and change it.

Explanation of script

  1. window.onload happens as soon as the page loads into the Window.

    What happens when the window loads, is that the rotate function begins.

  2. An array is created to hold the images.

    The counter is set to the first image.

    The Rotate Function

  3. The rotate function is defined. It's everything between the curly braces.

  4. The current image number is increased by 1.

  5. If the current image is the last image, we reset image number to 0 to start over again.

  6. Then we locate the HTML element that has an id of Banner and change its source to the next image in the array.

    We change the image src by referring to the image by its number in the array.

  7. setTimeout is another built-in method. It runs the rotate function and sets the timing for changing images. Here is set for every 3 seconds.