Reputation: 317
So I have a weird bug with my self-made jQuery image carousel. I also have already checked the suggested similar topics and they didn't help. So it's a simple six images with a next arrow and prev arrow. If you get to the end using the prev arrow then it loops to the last image successfully, but if you try to go back to the first image from the last using the next arrow it takes two extra clicks and after the first click it screws up the page and makes everything out of order. Any suggestions?
JavaScript
$('.arrow-prev').click(function() {
var currentSlide = $('.active-slide');
var prevSlide = currentSlide.prev();
if(prevSlide.length === 0) {
prevSlide = $('.slide').last();
}
currentSlide.removeClass('active-slide');
prevSlide.addClass('active-slide');
});
$('.arrow-next').click(function() {
var currentSlide = $('.active-slide');
var nextSlide = currentSlide.next();
if(nextSlide.length === 0) {
nextSlide = $('.active-slide');
}
currentSlide.removeClass('active-slide');
nextSlide.addClass('active-slide');
});
(Relevant) HTML
<div class="slider">
<div class="slide active-slide">
<img src="img/image-2.jpg">
</div>
<div class="slide">
<img src="img/image-3.jpg">
</div>
<div class="slide">
<img src="img/image-4.jpg">
</div>
<div class="slide">
<img src="img/image-5.jpg">
</div>
<div class="slide">
<img src="img/image-1.jpg">
</div>
<div class="slide">
<img src="img/image-6.jpg">
</div>
<a href="#" class="arrow-prev"><img src="img/Arrow-Prev.png" width="75px" height="75px"></a>
<a href="#" class="arrow-next"><img src="img/Arrow-Next.png" width="75px" height="75px"></a>
</div>
(Relevant) CSS
.slider {
display: block;
margin-left: 9%;
}
.slide {
display: none;
}
.active-slide {
display: block;
}
.slider img {
max-width: 90%;
margin-top: 15px;
}
.slider .arrow-prev {
margin-left: 13%;
}
.slider .arrow-next {
float: right;
margin-right: 25%;
}
Upvotes: 3
Views: 175
Reputation: 38252
You have two issues with your code for the next function.
The next()
element of the last slide will be the a
tag therefore the length is always > 0
. You can evaluate if the next is an "slide" element:
var nextSlide = currentSlide.next('.slide');
If nextslide doesn't exist you need to go to the first()
element:
nextSlide = $('.slide').first();
Thanks to @Jonathan Lam for the demo
Upvotes: 3
Reputation: 138267
nextslide=$(".activeslide")
in your if statement will not work because the activeslide is your current slide. The script will do nothing What about
nextslide=$(".slide").first()
?
Upvotes: 2