Reputation: 4142
I'm trying to get the slide/total count and got it working somehow. However, when I click next
and it goes back to the original first slide, it doesn't show 1/4
but it remains 4/4
.
JSFiddel: https://jsfiddle.net/zorw7yLe/
HTML:
<div class="num"></div>
<a class="next" href="#carouselExampleIndicators" role="button" data-slide="next"> -->>></a>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item item active">
<img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="First slide">
<div class="carousel-caption">
<h5>Title of the first image</h5>
<p>Some description of the first image</p>
</div>
</div>
<div class="carousel-item item">
<img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Second slide">
<div class="carousel-caption">
<h5>Title of the second image</h5>
<p>Some description for the second image</p>
</div>
</div>
<div class="carousel-item item">
<img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Third slide">
<div class="carousel-caption">
<h5>Title of the third image</h5>
<p>Some description for the third image</p>
</div>
</div>
<div class="carousel-item item">
<img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Fourth slide">
<div class="carousel-caption">
<h5>Title of the fourth image</h5>
<p>Some description for the fourth image</p>
</div>
</div>
</div>
</div>
JS:
var totalItems = $('.carousel-item').length;
var currentIndex = $('.carousel-item.active').index() + 1;
var down_index;
$('.num').html(''+currentIndex+'/'+totalItems+'');
$(".next").click(function(){
currentIndex_active = $('.carousel-item.active').index() + 2;
if (totalItems >= currentIndex_active)
{
down_index= $('.carousel-item.active').index() + 2;
$('.num').html(''+currentIndex_active+'/'+totalItems+'');
}
});
Upvotes: 0
Views: 130
Reputation: 97
I suggest you use bootstrap carousel events, you don't need to watch the click directly on your link :
https://getbootstrap.com/docs/4.0/components/carousel/#events
var totalItems = $('.carousel-item').length;
$('#carouselExampleIndicators').on('slide.bs.carousel', function (e) {
$('.num').html((e.to+1)+'/'+totalItems);
});
So your counter will keep track of the current slide
Also, your counter doesn't come back to 1/4 because of your condition (totalItems >= currentIndex_active), at the last slide if you add +2 on your index, that's 5, which is higher than totalItems (4)
You'll need a else to eventualy get the right number, but just use the bootstrap events
Upvotes: 3