I think what you're looking for is a slightly different approach, something like this:
$(function() {
var images = ['#page1_image', '#page2_image', '#page3_image'], i = 0;
function rotate() {
$(images[i]).fadeOut(10000);
i = (i+1)%images.length;
$(images[i]).fadeIn(10000, rotate);
}
$.each(images.slice(1), function(index, val) { $(val).hide(); });
rotate();
});
Give it a try here, if you don't fade smoothly back to the first image, your animation will have a jump, when the loop cycles. The above smoothly fades continuously, and works for any number of elements you want to cycle through, just add their selectors to the array.
The components are:
- Setup the array of selectors to fade...you can even cache the selectors here if they're not IDs it's a good idea, instead of strings.
- Rotate fades out the current, gets the next (wrapping around if needed) and fades it in, the
.fadeIn()
will call rotate
again when it's done.
- Last we're hiding all the images except the first (via
.slice()
), and starting the loop.