jQuery: a slideshow with timers

JavaScript timers allow us to create complex, repeated animations with very little effort. This turns out to be really useful with slideshows. We have a container with some images inside and we want to build a slideshow with jQuery. So far so good. The problem is that we want also that this slideshow enter in an infinite loop without breaking a sequence of jQuery animations. This is a little bit more complicated but you don't have to be afraid. First, understand timers. Second, use animations with animate(). Third, put all together. Let's see how.

As said before, we have just a container with few images inside. Let' start with assigning some styles to make only the first image visible:

#slideshow {
    width: 500px;
    height: 333px;
    margin: 2em auto;
    overflow: hidden;
}

#slideshow img {
    width: 100%;
    height: 100%;
    display: block;
    overflow: hidden;

}

Since we've set the overflow property to hidden, only the first image in the source will be visible. Now jQuery. First, let's create a timer using the setTimeout() global function:

$(document).ready(function() {

    var counter = -1;

    window.setTimeout(function() {

        counter += 1;

        $('#slideshow').find('img').eq(counter).animate({
            width: 0,
            height: 0
        }, 1000);

        if(counter == 4) {

           $('#slideshow img').animate({width: '100%', height: '100%'}, 500);

           counter = -1;

        }

        window.setTimeout(arguments.callee, 1000); 

    }, 1000);

});

We have initialized a counter that will be incremented each time the main timer runs. This counter serves as a numeric index to get our images. When the counter reaches its maximum, we reset it to its initial value. The animation is simple: the dimensions of each image are zeroed so that the next image can be shown. And so on. When all the image set is complete, we reset the dimensions of the image to their initial values. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.