how to create a simple automatic image rotator using jQuery

Rotate II by FatalBite on deviantART

I’ll explain a simple way to create an automatic image rotator using jQuery. First have a look at the demo page (opens in a new tab) to understand what we’re trying to accomplish. You can also [download id=”5″ format=”1″].

In the example, the initial image will be displayed on the left of a paragraph containing some sample text:

<div id="test">
  <img id="myImage" src="test1.png" alt="image test" />
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
</div>

First, we have to store the filenames of our images in an array. We also have to initialise a counter.

var images = new Array ('test1.png', 'test2.png', 'test3.png');
var index = 1;

The next step is to create the function which will rotate the images. We’ll call it rotateImage(). At the beginning, the currently displayed image fades out. Then, we load the next image from the images array (the counter we introduced before is being used here) and we fade it in. At the end of the function, we deal with the counter (either increment it, or reset it if all the imaged were displayed).

function rotateImage()
{
  $('#myImage').fadeOut('fast', function() 
  {
    $(this).attr('src', images[index]);
    
    $(this).fadeIn('fast', function() 
    {
      if (index == images.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

The last step is to call the rotateImage function repeatedly inside the $(document).ready function using setInterval. In the example, the function rotateImage() is being executed every 2.5 seconds (2500 milliseconds).

$(document).ready(function()
{
  setInterval (rotateImage, 2500);
});

The complete JavaScript code:

var images = new Array ('test1.png', 'test2.png', 'test3.png');
var index = 1;

function rotateImage()
{
  $('#myImage').fadeOut('fast', function() 
  {
    $(this).attr('src', images[index]);
    
    $(this).fadeIn('fast', function() 
    {
      if (index == images.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

$(document).ready(function()
{
  setInterval (rotateImage, 2500);
});

HTML:

<div id="test">
  <img id="myImage" src="test1.png" alt="image test" />
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
</div>

If you haven’t done it already, have a look at the demo page (opens in a new tab). You can also [download id=”5″ format=”1″].

Photo by ~FatalBite