Reputation: 601
I have a carousel with nine slides, the first of which has a class of 'active'.
<ul class='nav'>
<li class='left'>left</li>
<li class='right'>right</li>
</ul>
<ul class='carousel'>
<li class='active'></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
When the 'right' button is clicked, the active class needs to move to the next li (it also needs to be applied back to the first li after the last one).
And obviously, the active class needs to move in the opposite direction when the left button is clicked.
I tried the following, which works up to a point, but I don't know how to make the active class go back to the first li after the last one.
$('.nav .right').click(function(){
$('.carousel .active').removeClass('active').next().addClass('active');
});
Any help would be appreciated. Thanks.
Upvotes: 1
Views: 1638
Reputation: 388316
Try
var $carousel = $('.carousel');
$('.nav .right').click(function(){
var next = $carousel.children('.active').removeClass('active').next();
if(!next.length){
next = $carousel.children().first();
}
next.addClass('active');
});
$('.nav .left').click(function(){
var prev = $carousel.children('.active').removeClass('active').prev();
if(!prev.length){
prev = $carousel.children().last();
}
prev.addClass('active');
});
Demo: Fiddle
Another variation: Fiddle
Upvotes: 0
Reputation: 7401
It could certainly be improved, but the following code works for what you need to do:
$('.nav .right').click(function(){
var next = $('.carousel .active').removeClass('active').next();
if (next.length == 0) { next = $('.carousel li').first(); }
next.addClass('active');
});
Upvotes: 1
Reputation: 10994
$('.nav .right').click(function () {
$('.carousel .active:not(:last-child)').removeClass('active').next().addClass('active');
});
$('.nav .left').click(function () {
$('.carousel .active:not(:first-child)').removeClass('active').prev().addClass('active');
});
Upvotes: 0