Recently I was looking to add a collection of rotating images to my website, so I searched for an image rotater using jQuery. I found a number of very sophisticated libraries designed to rotate images, create slideshows and display fancy transitions. Any one of these would have met my needs. What I did not find was a simple bare-bonesjQuery example that I could use on my web site and enhance as I saw fit. So, I decided to build one form scratch. This example is simple enough that anyone with any jQuery experience at all can understand it. Hopefully, the explanation is clear enough that anyone can incorporate it into their own web site or use it as a starting point to learn jQuery.
Because this this blog is built on a framework that already uses jQuery, the image rotater can’s be directly embedded in this post. You can access an example by clicking on the image or at http://www.dchung.com/test/rotate.
Notice that this example uses the ever-present closure. Notice that the values: i, img and fig are defined in the ready() function. The values are used in the anonymous function called by the setInterval() function. The setInterval() function is called by the ready() function. By the time the anonymous function is called, both ready() and setInterval() have completed. The fact that the anonymous function can still access i, img and fig is a result of the closure.
The associated HTML5 is shown above. Notice that the src attribute and the <figcaption> values are specified in the jQuery not the HTML5.
Feel free to use this code on your own site or use it as a starting point. There are several other features that could be added like different transitions, radomization … and more.