jQuery: rotating header images

Rotating header images is an easy task with jQuery. All we need is an array where to store our images, a JavaScript timer and the fadeIn() and fadeOut() methods. Cycling through this array will produce the desired effect. Let's see the details.

The jQuery code is pretty intuitive:

var Rotator = new function() {

  var header = $('#headerimg', '#header');
  var img = $('img', header);
  var images = ['1.jpg', '2.jpg', '3.jpg'];
  
  this.rotate = function() {
  
    var timer = setTimeout(function() {
    
    
      img.fadeOut(2000, function() {
      
        img.attr('src', images[1]).fadeIn(2000, function() {
        
          img.fadeOut(2000, function() {
          
            img.attr('src', images[2]).fadeIn(2000, function() {
            
            
              img.fadeOut(2000, function() {
              
                img.attr('src', images[0]).fadeIn(2000);
              
              
              });
            
            
            });
          
          
          
          });
        
        
        });
      
      });
    
    
      setTimeout(arguments.callee, 12000);
    
    }, 100);  
  
  };

}();

$(function() {

  Rotator.rotate();


});

Our routine breaks down in the following steps:

  1. the image fades out
  2. its src attribute is set to the corresponding array's value
  3. the image fades in

You can see the demo below.

Demo

Live demo

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

Leave a Reply

Note: Only a member of this blog may post a comment.