www.cryer.co.uk
Brian Cryer's Web Resources

How to implement an automatic slide show using JavaScript

slide show

A slide show is where a number of images are displayed in sequence one after another. An example is shown here to the right of this paragraph.

To achieve this effect four things are required:

  1. An image placeholder
  2. A background container for the image
  3. JavaScript to run the slideshow
  4. The images to be shown

1. An image placeholder

This is a standard HTML image and is the image displayed before the slide show starts. The only things to bear in mind are the height and width of the image must be pre-set and that the image must be given a unique id. These are dealt with below under step 3.

As an example, this page uses the following HTML for its image:

<img border="1" src="emily01.jpg" width="200" height="200" id="EmilyPicture">

2. A background container for the image

A container is needed to hold an image behind the main image.

This container will be primed to show the next image. The JavaScript will then fade out the foreground image to reveal the new image loaded into this container. In this way the new image will appear to fade in - but in fact the way the logic works is to fade out the old image.

The JavaScript will take care of loading the correct image, and what is required in the HTML is to define a container. A <div> will do for this and, like the image, it must be assigned a unique id.

As an example, this page uses the following HTML for its background container:

<div id="EmilyPictureBackground">
  <img alt="slide show" src="emily01.jpg" width="200" height="200" id="EmilyPicture">
</div>

In this example the html for the image is also included. This is because the container must contain the image. Be sure that you don't include the image twice or it will not work as you expect!

It is probably a good idea to size the container to the same height and width as the image. Otherwise if you play with alignment there is a risk that the image shown in the background container will not be aligned with the foreground image and the fade effect will be ruined.

3. JavaScript to run the slideshow

This page uses the following JavaScript, which you are free to copy (or download it from here):

<script type="text/javascript">
// Browser Slide-Show script. With image cross fade effect for those browsers
// that support it.
// Script copyright (C) 2004-2011 www.cryer.co.uk.
// Script is free to use provided this copyright header is included.
var FadeDurationMS=1000;
function SetOpacity(object,opacityPct)
{
  // IE.
  object.style.filter = 'alpha(opacity=' + opacityPct + ')';
  // Old mozilla and firefox
  object.style.MozOpacity = opacityPct/100;
  // Everything else.
  object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
  var element=document.getElementById(id);
  var msNow = (new Date()).getTime();
  var opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
  if (opacity>=100)
  {
    SetOpacity(element,100);
    element.timer = undefined;
  }
  else if (opacity<=0)
  {
    SetOpacity(element,0);
    element.timer = undefined;
  }
  else 
  {
    SetOpacity(element,opacity);
    element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",10);
  }
}
function FadeInImage(foregroundID,newImage,backgroundID)
{
  var foreground=document.getElementById(foregroundID);
  if (foreground.timer) window.clearTimeout(foreground.timer);
  if (backgroundID)
  {
    var background=document.getElementById(backgroundID);
    if (background)
    {
      if (background.src)
      {
        foreground.src = background.src; 
        SetOpacity(foreground,100);
      }
      background.src = newImage;
      background.style.backgroundImage = 'url(' + newImage + ')';
      background.style.backgroundRepeat = 'no-repeat';
      var startMS = (new Date()).getTime();
      foreground.timer = window.setTimeout("ChangeOpacity('" + foregroundID + "'," + FadeDurationMS + "," + startMS + ",100,0)",10);
    }
  } else {
    foreground.src = newImage;
  }
}
var slideCache = new Array();
function RunSlideShow(pictureID,backgroundID,imageFiles,displaySecs)
{
  var imageSeparator = imageFiles.indexOf(";");
  var nextImage = imageFiles.substring(0,imageSeparator);
  if (slideCache[nextImage] && slideCache[nextImage].loaded)
  {
    FadeInImage(pictureID,nextImage,backgroundID);
    var futureImages = imageFiles.substring(imageSeparator+1,imageFiles.length)
      + ';' + nextImage;
    setTimeout("RunSlideShow('"+pictureID+"','"+backgroundID+"','"+futureImages+"',"+displaySecs+")",
      displaySecs*1000);
    // Identify the next image to cache.
    imageSeparator = futureImages.indexOf(";");
    nextImage = futureImages.substring(0,imageSeparator);
  } else {
    setTimeout("RunSlideShow('"+pictureID+"','"+backgroundID+"','"+imageFiles+"',"+displaySecs+")",
      250);
  }
  // Cache the next image to improve performance.
  if (slideCache[nextImage] == null)
  {
    slideCache[nextImage] = new Image;
    slideCache[nextImage].loaded = false;
    slideCache[nextImage].onload = function(){this.loaded=true};
    slideCache[nextImage].src = nextImage;
  }
}
</script>

If this script were to be used in a number of pages then it might be best included in a separate script file instead of being embedded directly in a web page. You should not need to modify the above in any way.

4. Images to be shown

The final step is to establish what images are to be shown as part of the slideshow and how long each image is to be displayed before moving onto the next one. As an illustration, this page uses the following:

<script type="text/javascript">
RunSlideShow("EmilyPicture","EmilyPictureBackground",
    "emily01.jpg;emily02.jpg;emily03.jpg;emily04.jpg",5);
</script>

This line should be included in the HTML file after the JavaScript that defines the  "RunSlideShow" function and below the image placeholder.

The "RunSlideShow" JavaScript function takes four values:

pictureID
The id given to the image. This identifies the image in which to run the slide show. This image will be replaced with each slide show image in turn. (The name was specified as part of step 1 above "An image placeholder".) In the HTML the picture name is specified by including a statement of the form:
id="pictureName"

in the img declaration statement.

backgroundID
The id given to the image container. This identifies the container that holds the image.
imageFiles
This is a string containing the names of the source files for each image to be displayed. Include a semi-colon (';') as a separator between the names of each image file.

It is very important that each image is the same size (height and width) as the original - or that it has the same aspect ratio (ratio of height to width) as the original. This is because each image is loaded into the same area or space that the original image occupied. If this images are not the same size then the browser will stretch the image to fit (and for example thus give the impression of very fat or very thin people) and this may be undesirable.

displaySecs
This is the number of seconds that each image is to be displayed for.

That's it.

A few other points to note for information:

<script type="text/javascript">
RunSlideShow("Key3","Key3Background","F3_key.gif;F4_key.gif",4);
setTimeout('RunSlideShow("Key4","Key4Background","F3_key.gif;F4_key.gif",4);',2000);
</script>

This script was updated in July 2008 to provide a cross browser image fade effect. The original article can be found here.