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:
- the image fades out
- its
srcattribute is set to the corresponding array's value - the image fades in
You can see the demo below.