Automatic Infinite Carousel
Posted on 13th August 2009 — Following on from the infinite carousel, there have been a number of requests asking how to make the scrolling action automatic, so I’ve gone ahead to explain how to achieve this.








Posted on 13th August 2009 — Following on from the infinite carousel, there have been a number of requests asking how to make the scrolling action automatic, so I’ve gone ahead to explain how to achieve this.
Watch
Watch jQuery Automatic Infinite Carousel screencast (Alternative flash version)
QuickTime version is approximately 8Mb, flash version is streaming.
View the demo used in the screencast
The Changes
To make the carousel automatically loop round by itself is pretty easy. In addition to automatic scrolling, I wanted to add the ability to make the scrolling pause when the mouse was over the carousel. To do this we need:
New Custom Event
As you’ll see from the original code we have the next and previous arrows. We could just trigger the next arrow click, but this feels a bit clunky.
So I’ve created a new event called “next” which is very similar to the next arrow being clicked:
This code goes directly after our events inside the plugin, since it needs to access the
currentPagevariable and thegotoPagefunction.We can test this custom event by calling the following in Firebug:
Next we need to make this call automatic.
Using Timers
There are two types of time:
setTimeout– runs a function in n milliseconds oncesetInterval– runs a function every n millisecondsWe’ll use
setIntervalto trigger the next call every 2 seconds. Inside the$(document).ready()function we add the following after we attach the plugin:Now the scrolling is automatic. Finally we need to only run this if the mouse isn’t over the
infiniteCarouselelement.Using Mouse Events
We’ll create a flag variable to track whether we should be automatically scrolling or not. When the mouse goes over the
infiniteCarousel, it will befalseotherwisetrue. Then within thesetInterval, we’ll only trigger the next event if we’re supposed to be scrolling:And that’s it. All we need to change to make the infinite carousel to run automatically.
You should follow me on Twitter here I tweet about jQuery amongst the usual tweet-splurges!