jQuery Tip: Simple Image Slideshow

Image slideshows have been around forever, but I thought I cover one from my Intro to jQuery Class.

The objective of this image slideshow is just have a series of image contained in a DIV element. By default the first image will display while the rest of the images (however many there are), will be hidden.

A CSS class is needed for first image to display, the rest by default will be hidden (display: none).

We create a function that does a few things.

First,  it will reference the image that has the class “show”. Be aware that I did not say the first image, because since this function will be run an infinite amount of times every 3 seconds, each image will have the class “show” added to it at one point.

Second, the next image is referenced using the next() jQuery method using shorthand ternary operator  to test if it is at the end of the set of images or not.

If there is another image in the set, the length jQuery property will return a value of 1, if  not, a value of 0 will be returned. Being (1) true, the first condition is set to the variable next. If it’s the last image (returning 0), we go back to the beginning by chaining siblings().first() methods. By chaining these two objects, we are asking to find the first image element in the group.

We need to call the siblings() jQuery method because we need a set for first() to work on.

Lastly, hide the current image and remove the class “show” and add it to the next image to identify it being the current image.

Note: You can chain other CSS class or jQuery methods for other effects as well.

Demo:  http://slideshow.javascriptworkshop.com/

Leave a Reply

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