Sunday, February 22, 2009

Make a JavaScript Slideshow

JavaScript slide shows are great for a lot of reasons. You can use them to spice up photo albums, add a little pizzazz to your home page, or even show a story, stop-motion-animation style. And one of the beauties of JavaScript is its reusability:Once you create your script, building a new slide show is just a matter of copying the code and pointing it at a new image folder.

To get an idea of the magic I'm talking about here, take a look at the slide show I made of the pics from my friend Azure's going away party. While Azure's parting was sweet, sweet sorrow, my loss is your gain:The script I used to create this slide show is easy to learn and modify. Just you wait and see!

Yes, in the lessons that follow, I'll show you how to build your very own slide show, then how to tweak it to your liking. (A hearty thanks goes out to Robert Bui - several parts of the JavaScript code I'm about to share are "inspired" by his script, which can be found at

What you'll need

One last thing I should mention before we begin building our script:If you are new to JavaScript or you get a little stuck during our lesson, you may want to read through Thau's JavaScript Tutorial to get a better understanding of JavaScript.

OK, let's get the slide show on the road!

Warming Up

Before we actually build our slide show script, we need to do a litle prep work first:

Bandwidth Considerations

When you build a slide show for your website, it's important to stop and consider your users before you start. The more images you pack into your slide show, the longer it takes to load. So if your average visitor is still stuck on dial-up, you really have to minimize the KB size of your images, and you should probably limit the number of images to ten or less.

Navigation is another element that requires some thought:I'll show you how to make "next" and "previous" buttons, which are a real must-have for dial-up users. But if bandwidth is no problem, go nuts!

And finally, user-initiated slide shows are a lot less intrusive then slide shows that start all on their own. Always give those slow-moving users a choice, they'll love you for it.

Make a Features List

When building a reusable script, it's a good idea to know ahead of time exactly what you want it to do. So let's make a list of the features we want, including all the pieces we need to build in our script.

We're going to want it to:

1. Have a sequential list of all our images so we can play them in order. 2. Have a way to play them randomly if we're feeling frisky. 3. Be able to change the delay between image changes. 4. Give the users some controls like pause, forward, and back. 5. Give us the option of auto-play or user initiated play.

Sizing the Images

When I build a slide show, I like to crop or resize all the images so they're all the same size. It's less jarring to the user, and it means the height and width tags will always stay the same, which keeps things nice and simple.

You may decide to use a bunch of images that are different sizes, but if you do, remember that you're going to have to either take out the width and height tags in your image tags (which will slow down the loading speed), or get a little trickier by adding some variables for width and height. Today, however, I'm just covering the one size fits all slide show.

Once you've got all your images the same size, you may want to consider simplifying your image names -- it's easier to manage, and you're less likely to have a typo break your script.

There are many great file renaming products on the market to help you out. On my Mac I've been using a handy-dandy shareware app called Quick Rename. For you Windows users, My friend Paul recommends a shareware app called The Rename Program.

And that should do it! We're ready to rumble.

Script from the Headlines

OK, Let's start by placing your script tag between the head tags of your webpage.

<head>     <title>Alanna's JavaScript slide show tutorial</title> 
<script language="JavaScript"> <!--
// --> </script> </head>

Next let's create a couple of global variables that we're going to need later on.

 var interval = 1500;   var random_display = 0;   var imageDir = "my_images/";  

The interval variable indicates the length of the pause we'll have between images. In JavaScript, 1000 is equal to one second, so I've set mine at 1.5 seconds.

The random_display variable tells the script whether we want our slide show to display our images in a random or sequential order. In this case, 0 is equal to sequential, 1 is equal to random.

Our imageDir variable will store the path name for our images so we'll only need to worry about the filename.

An Array of Arrays

Next we create an array of all the images we want in our slide show. An array is basically a list, and in our case, it will keep track of the image names as well as what number they are in the list.

For all the nitty, gritty details about JavaScript arrays, read Thau's array lesson.

For our array, let's create a variable to hold the image's number (or Index). We'll call that variable "imageNum" and assign it an initial value of 0. Keep in mind that JavaScript arrays start at 0, so the third item in the array has an index of 2, not 3.

Then we'll create a new array called "imageArray". We want the index to increase by one every time we add an image to the array. We can do that with imageNum++ (which is a JavaScript shorthand way of saying 'imageNum + 1') in the index brackets of the element in our new array. Then to have it equal a new element in the list, we'll call "imageItem". This contains the value of the variable "imageDir", which we've already created, plus the name of the image.

 var imageNum = 0;   imageArray = new Array(); 
imageArray[imageNum++] = new imageItem(imageDir + "01.jpg");

Then just copy and paste that line, change the image names for each one, and we've got ourselves an array.

 imageArray[imageNum++] = new imageItem(imageDir + "02.jpg");
imageArray[imageNum++] = new imageItem(imageDir + "03.jpg");
imageArray[imageNum++] = new imageItem(imageDir + "04.jpg");
imageArray[imageNum++] = new imageItem(imageDir + "05.jpg");

We need to know how many items we've got in our array, total, so let's create a variable called totalImages that's equal to the length of imageArray. We can do this with ".length", which is a handy property that's built into arrays.

var totalImages = imageArray.length;

Onward, Upward with Forward, Backward

We'll need to write a couple functions to tell the script what to use for each image's location. The first function below creates the image location, the second one returns the location.

 function imageItem(image_location)
this.image_item = new Image();
this.image_item.src = image_location;
function get_ImageItemLocation(imageObj)

Since we might want to display our images randomly. we need a function to generate some random index numbers for us.

 function randNum(x, y) {    var range = y - x + 1; 
return Math.floor(Math.random() * range) + x; }

Get the Next Image

Now let's tell the script how to get the next image in the sequence. First, if we've chosen to display the images randomly, we make the imageNum equal to the random number, while making sure it's not more than the total number of images in the array.

If it's not random, we just increment the imageNum by 1. Then to make sure we don't go over the total number of images, we use the handy dandy modulus operator (%). This will give us a remainder of 1, as soon as we go over the total number, but will just return the incremented imageNum until then. So when we go over, we go back to the beginning! Neat huh?

if (random_display)
imageNum = randNum(0, totalImages-1);
else {
imageNum = (imageNum+1) % totalImages;

Now that we know which image to display, we just need to return the value:

  var new_image = get_ImageItemLocation(imageArray[imageNum]); 
return(new_image); }

Adding a Previous Button

Since we've already done most of the work, let's add a couple of functions so the user can go both forwards and backwards through our slide show. First, let's assign a value by creating a getPrevNum variable. It's based on our getNextImage variable but I've changed the +1 to a -1.

 function getPrevImage()
imageNum = (imageNum-1) % totalImages;
new_image = get_ImageItemLocation(imageArray[imageNum]);

Then we'll add a function to call the right value for the new_image variable we've been using.

 function prevImage(place)
var new_image = getPrevImage();
document[place].src = new_image;

The switch image function

Phew, we're almost there! We'll now create a function that will tie all our hard work together. We'll call it switchImage, use the getNextImage function we just created, and use JavaScript's setTimeout method to change the image depending on what value we initialized in our "interval" variable.

var new_image = getNextImage();
document[place].src = new_image;
var recur_call = "switchImage('"+place+"')";
timerID = setTimeout(recur_call, interval); }

Play Time!

We're done with the script part of our tutorial, all that remains is plugging the right stuff into our HTML.

Here's what your image tag should look like. Make sure you give it a name so the script will know which image you're talking about. I'll call ours "slideimg." Remember to change your height and width tags to the appropriate values or take them out if you're using images with different sizes.

<img name="slideImg" src="27.jpg" width=500 height=375 border=0>

Adding the Controls

To create a play button, use an onClick in an anchor tag. You don't have to be as boring as me here, you can wrap this anchor tag around any image you like, or just use a regular text link.

<a href="#" onClick="switchImage('slideImg')">play slide show</a>

I put the "#" in there so that it'll work on all browsers. Some browsers will ignore the anchor tag if there is no URL specified. The "switchImage" function calls the getNextImage function.

To pause our slide show, we can use JavaScript's built-in clearTimeout method, like so:

<a href="#" onClick="clearTimeout(timerID)"> pause</a>

Our previous button will look like this:

<a href="#" onClick="prevImage('slideImg'); clearTimeout(timerID)"> previous</a>

And for the Next button, I sort of cheated a bit. This starts up the switchImage function and then stops it again after it increments by 1.

<a href="#" onClick="switchImage('slideImg'); clearTimeout(timerID)">next </a>

Auto Start

If you'd like your slide show to start up as soon as the page loads (again, this might alienate your slower, dial-up users, so use with caution), just add an onLoad to your body tag, like this one.

<body onLoad="switchImage('slideImg')">

Labels: ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home