In this tutorial, we will go over a simple slideshow example built with jQuery. Feel free to use the example code shown below and build upon it so you can add more sophisticated components for your slideshow. Using the example below, you can control how many images are included in the show, the duration of each slide, as well as the fading in and out speed between images.

The HTML

The only HTML code needed is a simple

containing all of your (image) elements. Here is an example…

The CSS

There is very little CSS code that needs to be applied to our slideshow container and its child elements. The following CSS markup sets the parent container’s position to relative so that we can set absolute positioning on the image elements within the parent container. Then, set the images to display equal to none. The images will be faded in and out using jQuery.

The jQuery

As you can see in the example below, there is not much jQuery code needed for this example. The first four lines are used to set up our variables. imgDuration is used to set the amount of time (in milliseconds) the image will be displayed. fadeSpeed is used to control (in milliseconds) the amount of time the fadeIn and fadeOut effect lasts. The container variable is used to capture the slideshow-container object (the div element containing the images). And the curIndex variable is used to keep track of which image element we are working with. The function called slideShow() is where the magic happens. There are only three lines of code. The first line fades out the current image, while the second line fades in the next image. You will notice that we are using a conditional operator in the second line. We use the conditional operator (much like an if..then..else block) to determine what to do based on the current image. If we are in the last image, we reset the curIndex variable back to ‘0’ to start the process all over again. Here is the jQuery code… Here is more information about how the conditional operator works.

Complete Example