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.


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:

  1. An event we can trigger to go to the next panel
  2. A timer to keep firing the new custom event
  3. Mouseover and mouseout events to pause the timer

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).bind('next', function () {
  gotoPage(currentPage + 1);

This code goes directly after our events inside the plugin, since it needs to access the currentPage variable and the gotoPage function.

We can test this custom event by calling the following in Firebug:

>>> $('.infiniteCarousel').trigger('next');

Next we need to make this call automatic.

Using Timers

There are two types of time:

  • setTimeout – runs a function in n milliseconds once
  • setInterval – runs a function every n milliseconds

We’ll use setInterval to trigger the next call every 2 seconds. Inside the $(document).ready() function we add the following after we attach the plugin:

setInterval(function () {
}, 2000);

Now the scrolling is automatic. Finally we need to only run this if the mouse isn’t over the infiniteCarousel element.

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 be false otherwise true. Then within the setInterval, we’ll only trigger the next event if we’re supposed to be scrolling:

var autoscrolling = true;

$('.infiniteCarousel').infiniteCarousel().mouseover(function () {
  autoscrolling = false;
}).mouseout(function () {
  autoscrolling = true;

setInterval(function () {
  if (autoscrolling) {
}, 2000);

And that’s it. All we need to change to make the infinite carousel to run automatically.