Simplest jQuery Slideshow & Plugin


The HTML was very straightforward: a DIV with some IMGs in it.

In thinking about the CSS, I decided to just lock all the images into the same place using absolute positioning.

jQuery Slideshow

Now to think about the slideshow. First, I knew that I’d want to hide all the images except the first one.

You have to remember that the image index starts at 0. That means that we want all images after the first one to be hidden.

Next, I need a setInterval to iterate through the images every few seconds.

From here, I started writing this out piece by piece to get what I wanted. I needed the first image to fade out.

After that, I need the next image to fade in.

Then I needed to take the first image and throw it onto the end of the stack.

The end() resets jQuery’s internal reference back to the original selection. That way, it’s the :first-child that I’m appending to the end of the .fadein element and not the next('img').

That’s it?

Well, yes. That’s it.

Check out the Demonstration page to this this little script in action.

Is there an even simpler way to do this? (Some ideas that I haven’t tried: Is specifying img in next() necessary? Could I have used eq(0) instead of :first-child to save a couple bytes?)

Convert to into a jQuery plugin:

Now you can use something like this to invoke the slideshow on an element:

As you can see, I’ve added a timeOut parameter. The default value is 3000 (I just took this from your code) but this can easily be specified:

Fully-Fledged jQuery plugin

It can be called with timeout and speed parameter values.

You may use it like this:

Leave a Reply

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