Reputation: 49
I have been working on coding a slideshow code, which works if you have one slide show running, however, I wanted multiple. The code selects the active class, which is successfully done for two slide shows, and removes and adds the class, which it again successfully does, however, it cannot select the next slide once it loops once.
My previous code looked like this:
setInterval(function(){
var $currentSlide = $('.active');
var $nextSlide = $currentSlide.next();
if ($nextSlide.length === 0){
$nextSlide = $('.jumbotron').first();
}
$currentSlide.fadeOut(500).removeClass('active');
$nextSlide.fadeIn(500).addClass('active');
}, 9000);
I attempted to use an each function, however, it does not seem to be working at all:
setInterval(function(){
$('.slideshow').each(function(){
var $currentSlide = $(this).find('.active');
var $nextSlide = $currentSlide.next();
if ($nextSlide.length === 0){
$nextSlide = $(this).firstChild();
}
$currentSlide.fadeOut(500).removeClass('active');
$nextSlide.fadeIn(500).addClass('active');
});
}, 1000);
Any help would be much appreciated. Thank you.
Upvotes: 0
Views: 33
Reputation: 676
Is this what you are looking for? Your code was fine except $nextSlide = $(this).firstChild();
which gave an error. Just changed that to $nextSlide = $this.children().first();
setInterval(function() {
$('.slideshow').each(function() {
var $this = $(this);
var $currentSlide = $this.find('.active');
var $nextSlide = $currentSlide.next();
if ($nextSlide.length === 0) {
$nextSlide = $this.children().first();
}
$currentSlide.fadeOut(500).removeClass('active');
$nextSlide.fadeIn(500).addClass('active');
});
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slideshow">
<div class="active">Slide 1</div>
<div>Slide 2</div>
</div>
<div class="slideshow">
<div class="active">Slide 3</div>
<div>Slide 4</div>
</div>
Upvotes: 1