Reputation: 67
I'm trying to create an image rotator where one image will fade into the next and so on until it loops back to the first image. I got the first two images to work correctly but the remaining 3 don't fade correctly. They just jump into view.
I know I still need to account for the reaching the end of the rotation. I haven't taken care of that yet because I'm just trying to get the first round of rotation to work.
What am I missing to get this to work correctly?
My HTML:
<div id="imageRotator">
<div id="image01" class="current">
<img src="images/imageRotate01.jpg">
</div>
<div id="image02" class="next">
<img src="images/imageRotate02.jpg">
</div>
<div id="image03" class="hidden">
<img src="images/imageRotate03.jpg">
</div>
<div id="image04" class="hidden">
<img src="images/imageRotate04.jpg">
</div>
<div id="image05" class="hidden">
<img src="images/imageRotate05.jpg">
</div>
</div>
My CSS:
#imageRotator div {
position: absolute;
}
.current {
z-index: 1;
}
.next {
z-index: 0;
}
.hidden {
z-index: -1;
}
My jQuery:
$(document).ready(function() {
var firstImage = $('#image01');
var currentImage, nextImage;
setInterval(rotateImages, 2000);
function rotateImages() {
currentImage = $('div.current');
nextImage = $('div.next');
//the first image fades away
currentImage.animate({opacity: 0}, 2000, function() {
currentImage.removeClass('current');
});
//bring the second image into view
nextImage.animate({opacity: 1}, 2000, function() {
//make the new image the current image
nextImage.removeClass('next').addClass('current');
//the next image in the rotation becomes the 'next' image
nextImage.next().addClass('next').removeClass('hidden');
});
}
});
Upvotes: 0
Views: 361
Reputation: 5621
You haven't set a zero opacity
by default so there is no animation for opacity
for the elements after the first. Try setting it to 0 to all the elements but the first and see what happens.
#imageRotator div {
position: absolute;
width: 30px;
height: 30px;
outline:1px solid red;
background:red;
opacity: 0;
}
#imageRotator div:first-child{
opacity:1;
}
.current {
z-index: 1;
}
.next {
z-index: 0;
}
.hidden {
z-index: -1;
}
DEMO: http://jsfiddle.net/pavloschris/N3gXd/
Upvotes: 1