Reputation: 11
I have a simple slideshow of images and use jQuery to fade out one and fade in another, but the effects only work after the first time.
jQuery:
setInterval(function() {
jQuery('#slider > div:nth-child(2)')
.fadeOut()
.next()
.fadeIn()
.end()
.prependTo('#slider');
jQuery('#slider > div:nth-child(1)')
.fadeOut()
.next()
.fadeIn()
.end()
.prependTo('#slider');
}, 5000);
CSS:
#slider > div:nth-child(1){
display:none;
}
Upvotes: 1
Views: 369
Reputation: 58432
I think it is to do with your prepending and hiding the first element. Try this instead (comments in code explaining what is happening):
setInterval(function() {
// get first and second slides:
var slide = jQuery('#slider > div:nth-child(1)'),
nextSlide = slide.next();
// fadeOut the first slide
slide.fadeOut('slow', function () {
// when animation is finished fade in second slide and move first slide to second place ready for animation to repeat in reverse
nextSlide.fadeIn('slow').after(slide);
});
}, 5000);
#slider {
position: relative;
}
#slider > div:nth-child(2) {
display: none; // always hide 2nd slide
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider">
<div>Test</div>
<div>Test1</div>
<div>Test2</div>
<div>Test3</div>
</div>
Upvotes: 2