Simplest jQuery Slideshow - Snook.ca
Simplest jQuery Slideshow
A friend was looking at doing a simple slideshow. The requirements were very straightforward:
- No animation controls. eg: play, stop.
- Images should cross-fade.
Her instinct was to find an existing jQuery plug-in and revise it to work to her needs. That would seem simple enough but if you do a search for jQuery slideshows, you'll find that there are plenty of them and they are filled with plenty of functionality.
Using an existing plug-in wasn't very practical and hard to work with. I had even recommended a script that I, myself, had written but she quickly realized it didn't meet the requirements.
I put my thinking cap on and decided to write a script from scratch. "Under 20 lines," I exclaimed! In the end, it turned out much simpler than even I predicted.
(If you're a TL;DR kinda person, check out the demo.)
HTML and CSS
The HTML was very straightforward: a DIV with some IMGs in it.
<div class="fadein"> <img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg"> <img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg"> <img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg"></div>In thinking about the CSS, I decided to just lock all the images into the same place using absolute positioning.
.fadein { position:relative; width:500px; height:332px; }.fadein img { position:absolute; left:0; top:0; }jQuery Slideshow
Now to think about the slideshow. First, I knew that I'd want to hide all the images except the first one.
$('.fadein img:gt(0)').hide();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
setIntervalto iterate through the images every few seconds.setInterval(function(){ },3000);From here, I started writing this out piece by piece to get what I wanted. I needed the first image to fade out.
$('.fadein :first-child').fadeOut()After that, I need the next image to fade in.
.next('img').fadeIn()Then I needed to take the first image and throw it onto the end of the stack.
.end().appendTo('.fadein')The
end()resets jQuery's internal reference back to the original selection. That way, it's the:first-childthat I'm appending to the end of the.fadeinelement and not thenext('img').That's it?
Well, yes. That's it.
$(function(){ $('.fadein img:gt(0)').hide(); setInterval(function(){ $('.fadein :first-child').fadeOut() .next('img').fadeIn() .end().appendTo('.fadein');}, 3000); });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
imginnext()necessary? Could I have usedeq(0)instead of:first-childto save a couple bytes?)
Digging the utter simplicity of this, but it could definitely be enhanced performance and modularity wise.
