jQuery A Simple Slideshow Tutorial

For starters, our main goal should be keeping the markup as clean as possible:

Now let’s use CSS to position the images on top of each other and bring the active image to the top level with z-index:

Due to absolute positioning, we need to define the height of the slideshow DIV. Also, notice that we defined three different z-index. We will manipulate these soon using jQuery.

For the slideshow animation we are going to switch between each photo at a set rate. So let’s start by writing a function that brings in a new photo on top of the last active image:

Here we set a JavaScript interval to call slideSwitch() every 5 seconds. Then slideSwitch() applies the CSS class active to bring the next image to the top of the stack. Since we will select the images more than once within slideSwitch(), we define the variables $active and $next for selector performance.

Next we should incorporate a fade animation. For a gallery like this, fade in and fade out are identical, but let’s not forget to think about what we fade against:

We start by applying the last-active class we defined earlier. Since .last-active falls after .active in the stylesheet, the z-index of 9 takes priority, and the top image drops back a level. Next, we set the opacity of the new image to 0 so that we can fade it in using the animate() function. Finally, we attach a callback to remove the z-index classes from the previous image when animate() completes.

Although our slideshow is working well, we should make it more robust by building in some default variables. First, let’s define a default active image, in case we need to put less stress on the back-end. Also, we can use defaults to make the gallery animation loop.

We first define a default image for the $active variable, which interestingly enough needs to be the last image on the stack. This is because through absolute positioning, the last image appears on top, and we need to start with it if we want to avoid any flicker.

For the loop it is pretty simple: all we have to do is point the $next variable to the first image once it has gotten to the end of the line.

If you want to improve this function, try setting the animation speed with a variable so the main slideshow function can be thrown into the core and left alone. Also, this slideshow is easily converted to support DIV’s instead of IMG’s—try programming a slideshow with more content.

Now for a challenge: the gallery flickers when the images first load, but it can be fixed without touching the JS or markup at all. Bonus points to whoever figures it out and posts a comment.

Download the complete slideshow here

Leave a Reply

Your email address will not be published. Required fields are marked *