Paul McFedries' Web Home


Cycling Through a Series of Images

This page shows you how to use JavaScript to cycle through a series of images. The images below show an example. Click the forward button (the right-pointing arrow) to increase the value in the image above it; click the reverse button (the left-pointing arrow) to decrease the value:



Here are the instructions:
  • This script is shown below. Copy everything between the <SCRIPT> and </SCRIPT> tags and insert it between the </HEAD> and <BODY> tags.

  • You have to define the number of images you want to display by altering the value in the following line:
        var NumberOfImages = 10
    
  • You specify the image files by editing the following lines:
        img[0] = "digital0.gif" 
        img[1] = "digital1.gif"
        img[2] = "digital2.gif"
        img[3] = "digital3.gif"
        img[4] = "digital4.gif"
        img[5] = "digital5.gif"
        img[6] = "digital6.gif"
        img[7] = "digital7.gif"
        img[8] = "digital8.gif"
        img[9] = "digital9.gif"
     
  • To call the functions, set up your links and use javascript:PreviousImage() and javascript:NextImage() as the HREF value, like so:
    <A HREF="javascript:PreviousImage()">
    <IMG SRC="reverse.gif" BORDER=0></A>
    <A HREF="javascript:NextImage()">
    <IMG SRC="forward.gif" BORDER=0></A>
    
  • In your page, add an <IMG> tag and set it's NAME attribute to "VCRImage", like this
    <IMG SRC="whatever.gif" NAME="VCRImage">
    
Here's the full script:
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify 
// the number of images
var NumberOfImages = 10

var img = new Array(NumberOfImages)

// Use the following variables to specify the image names:
img[0] = "digital0.gif"
img[1] = "digital1.gif"
img[2] = "digital2.gif"
img[3] = "digital3.gif"
img[4] = "digital4.gif"
img[5] = "digital5.gif"
img[6] = "digital6.gif"
img[7] = "digital7.gif"
img[8] = "digital8.gif"
img[9] = "digital9.gif"

var imgNumber = 0

function NextImage()
{
    imgNumber++
    if (imgNumber == NumberOfImages)
        imgNumber = 0
    document.images["VCRImage"].src = img[imgNumber]
}

function PreviousImage()
{
    imgNumber--
    if (imgNumber < 0)
        imgNumber = NumberOfImages - 1
    document.images["VCRImage"].src = img[imgNumber]
}

//-->
</SCRIPT>


Copyright © 1995-2008 Paul McFedries and Logophilia Limited