This recipe shows you how to create a simple image slideshow that works in modern browsers. This example starts by declaring an array containing image paths. We have declared an image control on the page. When the page loads, the image path of this control is set to the last element of the array. I will explain shortly why this is needed.

var $imageSlide = $('img[id$=imageSlide]');// set the image control to the last image$imageSlide.attr('src', imgs[cnt-1]);

We then use the JavaScript setInterval() function which delays execution of the Slider function for a specific time, in our case 3000 millisecond(3 seconds). The advantage of a setInterval() function is that it continues to repeat the process of triggering the function at a specified interval, thereby sliding the images in a cycle. If you want to pause the slideshow, use the clearInterval() function.

Note: Since the Slider function is first called after a 3 seconds delay, hence we explicitly set the image control source to the last image path in the array. If we do not do so, the user does not see an image for the first 3 seconds.

With every loop, we set the image control source to the next element in the array using the expression imgs[(imgs.length++) % cnt] and apply the fadeIn() and fadeOut() effect.

12 comments:

I think this is the right idea. I have not tested, the following comments.

1. The call to imgs.length++ will increment this value every 3 seconds. You will lose the intent of the variable. Seems like you want to have a copy (var index = imgs.length for instance) and then increment that variable.

2. The setInterval option does not take into consideration the load time of the images. If for example, it takes 2.5 seconds to load, then the image will be shown for 0.5 seconds. This will occur during the initial caching of the images.

I wouldn't call it a bug. In the book, I have mentioned a plugin that caches images before it can be used, and yes as you suggest, that's the way to go. My intention here was to focus on creating a simple image slide show.