Re: Simplest jQuery slideshow

2009-12-23

I read this post from Jonathan Snook a while ago but I wasn't able to respond to it right there and then.

I'm not going to post a shorter code here. One line is one line and I'm sure it could have been shorter. Thomas Fuchs posted his version as well, in a response to it.

Here's my version:

Code: (JS)
var n=0, c = CDE.toDom('fadein').getElementsByTagName('img'), f = function (){
CDE.wrap(c[n]).fadeOut();
n = ((n||0) + 1) % c.length;
CDE.wrap(c[n]).fadeIn();
};
f();
setInterval(f, 3000);

Live demo here.

It fetches the image elements (using the DOM...) who are a child of given id and fades them alternating using n to track the current index. Every time the function is called the current index is faded out, the pointer is incremented and the new index is faded in. Repeat every 3 seconds.

It's not necessarily shorter, and uses my own library, but it makes a point. All that's needed for a simple slideshow is a proper fading function... Mine's a bit overpowered, but does the job nevertheless.

And short code should not be counted in terms of "lines" these days. Virtually anything can be chained together. Either count the bytes or the function and method calls.

Of course, there's also the question of how much a library could take over. I could have changed CDE to accommedate the fadeing in and out in one line, only having to increase the counter (but I do have a bit more freedom in release cycles for my lib :p). In fact, I could have included the function to do it all at once, supplying only the Id. But that wasn't the point :)

So, in short, it's fading that makes a slideshow these days. Anything else is sugar.