Overview
Arrays can hold more than names. They can hold numbers, other JavaScript objects, properties, etc. In this lesson we'll learn how to use an array of file path names (to image files) to make a slicker and leaner slideshow than we learned in Beginning JavaScript.
Here's an example. It looks just like the slideshow we made using a bunch of "setTimeout()s" looping back to each other. But, it's much more efficient.
Imagine you have 100 images to cycle through, or even just a dozen. That's a lot of "setTimeout()s" to code. We can get around using a "setTimeout()" for each image by putting the paths to the image files in an array and then cycling through the array for an image rollover.
We won't be using a FOR loop to cycle through the array this time. It's tricky to slow the FOR loop down enough for a slideshow. For our current example, we'll make a custom loop that's controlled by simple addition and an IF statement.
The idea goes like this. We make an array of path names to image files. Then we just declare a variable to act as a counter. No FOR statement needed. Now we use a "setInterval()" that runs a second function that changes the image and then adds 1 to the counter for incrementing.
An IF statement is used to detect when the counter runs out of bounds, and resets it. In our example, "out of bounds" means the variable becomes greater than the number corresponding to the last object in the array. If this happens, the array won't have an object and an error will occur.
Making The Array
We'll begin making our advanced slideshow by making the array of path names to our images. In the sample below, both the page and the images are in the same directory (folder), so I only need to use the images' filenames alone:
<script language="JavaScript">
pix = new Array ("screw.jpg","washer.jpg","capnut.jpg","coffee.gif");
</script>
You could also make the array by directly assigning the the objects to the array:
<script language="JavaScript">
pix = new Array();
pix[0] = "screw.jpg";
pix[1] = "washer.jpg";
pix[2] = "capnut.jpg";
pix[3] = "coffee.gif";
</script>
You'll end up with the same array either way. If your images aren't in the same folder as the page, you'll need to make more complex file paths. Here's an example:
pix[0] = "images\/screw.jpg";
...
Notice the little red backslash. The path we want to use is "images/screw.jpg", but the regular slash (/) might cause some problems because it means "divide by" to JavaScript.
I used the backslash (\) "escape character" to tell the browser that I want the regular slash (/) presented as part of the string. I don't want to divide. This isn't always a problem when using regular slashes in strings, but it is something you need to be aware of.
Setting Up The Interval
We want the slideshow to begin running as soon as the page loads, so I've used the "onLoad" event in the <body> tag to get things started. The "onLoad" event calls a function called "slideshow()".
<body onLoad="slideshow()">
All the function "slideshow()" does is set up the the interval, or pace, at which we want the images to change. Use the "setInterval()" method to do this.
<script language="JavaScript">
pix = new Array();
pix[0] = "screw.jpg";
pix[1] = "washer.jpg";
pix[2] = "capnut.jpg";
pix[3] = "coffee.gif";
function slideshow(){
setInterval("change()", 1000);
}
</script>
You should remember the "setInterval()" method from Advanced JavaScript Lesson 3. It has two parts in the parentheses. First is the function you want to run, and, second, is how frequently to run it (in milliseconds). Our "setInterval()" will run the function "change()" every second (1000 milliseconds).
It's the "change()" function that actually changes the image and increments (adds to the variable used for counting) the loop. As you will often see in Advanced JavaScript, it usually takes two or more functions referring to each other with "setTimeout()s" or "setInterval()s" to make a timed or looped effect if a FOR loop is not being used.
Making The Display Function
The "change()" function must do three things. First, it must change the image displayed. Secondly, it must add 1 to the variable we'll be using as a counter. Finally, it must detect when the end of the array has been reached and reset the slideshow to run again.
To begin we need to make a variable we can use to count and cycle through the array. I'm going to call mine "i" and initialize it to zero:
<script language="JavaScript">
pix = new Array();
pix[0] = "screw.jpg";
pix[1] = "washer.jpg";
pix[2] = "capnut.jpg";
pix[3] = "coffee.gif";
var i = 0;
function slideshow(){
setInterval("change()", 1000);
}
</script>
The biggest thing to note about declaring this variable is that I declared it outside any functions. This makes it a global variable. A global variable can be used by any number of functions although it will only be used by one in this lesson.
A variable declared inside a function is called a local variable and can only be used by the function it is declared in. (Yes, there are ways around this, but don't worry about them right now.)
The reason I made the counting variable a global variable is that I want it to change as the "change()" function runs. If I declared the counting variable in the "change()" function, it would reset to zero each time the "change()" function ran. To keep it from resetting like that, I declared it outside of all functions.
Now that we've got our variable declared and initialized to 0, we can begin making our "change()" function and changing the image display.
<script language="JavaScript">
pix = new Array();
pix[0] = "screw.jpg";
pix[1] = "washer.jpg";
pix[2] = "capnut.jpg";
pix[3] = "coffee.gif";
var i = 0;
function slideshow(){
setInterval("change()", 1000);
}
function change(){
document.images.pic.src = pix[i];
i = i + 1;
...
}
</script>
The first thing "change()" does is to change the image display. (Note: I NAMEd the <img> "pic".) It changes the image to one of the images in the "pix" array depending upon the value of "i". The first pass through, "i" will equal its initial 0, so "screw.jpg" will continue to be displayed.
The second statement in "change()" increments the value of "i". It adds 1 to the current value, so now "i" equals 1 (0+1=1). When "change()" is run again, "pix[1]" (or "washer.jpg") will be displayed.
The IF Control
There's one last thing we need to do to complete the "change()" function. We need to detect when the end of the array is reached so we can reset "i" before an error occurs. We'll use an IF statement to determine if "i" is greater than the number corresponding to the last object in the array (pix[3] = "coffee.gif").
<script language="JavaScript">
pix = new Array();
pix[0] = "screw.jpg";
pix[1] = "washer.jpg";
pix[2] = "capnut.jpg";
pix[3] = "coffee.gif";
var i = 0;
function slideshow(){
setInterval("change()", 1000);
}
function change(){
document.images.pic.src = pix[i];
i = i + 1;
if (i > (pix.length-1)) {i = 0}
}
</script>
Remember that the number of the last object of an array is always 1 less than the array's length. The IF tests to see if "i" is greater than the number corresponding with the last object in the array. If it is greater, "i" is reset to 0 with "{i = 0}". Simple as that.
Loops made like the one above are much more flexible than FOR loops. You can easily establish all sorts of increments for numerous variables to make complex looped effects.
A Walk-Through Of The Effect
We've covered a lot of ground on how to use "setInterval()" and an array to make an endless loop for a slideshow. Here's a brief walk-through of what's happening to create the slideshow effect.
First the page loads and I've included a standard image preloading script so the images will (hopefully) load before the effect starts running. As the page loads, the array is made and put into memory. The variable "i" is declared and initialized to 0.
The <img> called "pic" displays its initial "screw.jpg".
When the page has loaded, the "onLoad" event calls the "slideshow()" function. This function is a "setInterval()" set to run the "change()" function every second (1000 milliseconds).
The "change()" function is called by the "setInterval()" and runs. The first statement sets the image to display the first image in the array (pix[0]). That's still "screw.jpg" so we don't see an initial change.
The "change()" function's second statement causes "i" to increase (increment) by 1. The value of "i" is now 1 (0+1=1). This new value is tested by the IF statement to see if it is "in bounds". It is, and, in one second, the "change()" function will run again.
On the second pass, the "change()" function's first statement now displays pix[1], which is the image "washer.jpg". Another 1 is added to "i", so "i's" value is now 2 (1+1=2). This value is tested in the IF statement.
The above continues until "i" equals 4. At that point, the IF statement detects the "out of bounds" condition and resets "i" to zero. The loops begins again with pix[0] -- "screw.jpg".
This continues as long as the page is loaded. In the next tutorial we'll learn how to turn this on and off, but for now, just be concerned on getting it running and looping properly.
Summary & Exercises
FOR loops have some limitations. Making timed events is one of these limitations. We can make timed events using "setInterval()" or "setTimeout()" and making our own incrementing (counting) scheme.
The two main parts of a custom incrementing scheme is to 1) initialize and add to a "counter" variable, and 2) detect when the "counter" variable has run beyond the limits of the array (or whatever else it is counting).
Incrementing can be done with simple math like addition and subtraction. An IF statement is used to detect an "out of bounds" condition and take action, like resetting the counter variable to a given value.
See if you can make the slideshow run backward by changing the incrementing and IF condition. Hints: i = i - 1. IF (i < 0)...
Make an array of at least 10 images and make a slideshow of them. This will really show you how much easier it is using an array over ten "setTimeout()s".
To Next Advanced JavaScript Lesson
Back To Advanced JavaScript Index
|