simba
simba

Reputation: 15

Jump to last slide on Bootstrap carousel

I'm creating a Carousel with bootstrap and I'd like to create a link that jump directly to the last slide in the carousel (with n slides, not a fixed number). I tried to resolve the problem assigning the class active to the last div in the this way:

$(".last").click(function(){
    $('myCarousel div').removeClass('active'); 
    $('myCarousel div:last-child').addClass('active'); 
});

But, this works if I have just a carousel in my page, but if the carousels are more than one the link go to the last slide on all the carousels. How can I resolve the problem? Here is an example of the code:

<div id="myCarousel1" class="carousel slide"> 
 <div class="carousel-inner" role="listbox">
   <div class="item active slide">
    <img src="http://placehold.it/350x150">
   </div>
   […] other items
 </div>    
</div>
<ul>
 <a href="#myCarousel1" data-slide="prev"><li>Prev</li></a>
 <a href="#myCarousel1" data-slide="next"><li>Next</li></a>
 <a href="#myCarousel1"><li class="last">Last</li></a>
</ul> 

<div id="myCarousel2" class="carousel slide"> 
 <div class="carousel-inner" role="listbox">
   <div class="item active slide">
    <img src="http://placehold.it/350x150">
   </div>
   […] other items
 </div>    
</div>
<ul>
 <a href="#myCarousel2" data-slide="prev"><li>Prev</li></a>
 <a href="#myCarousel2" data-slide="next"><li>Next</li></a>
 <a href="#myCarousel2"><li class="last">Last</li></a>
</ul> 

<script> 
$(document).ready(function(){
 $(".last").click(function(){
  $('[id^="myCarousel"] div').removeClass("active"); 
  $('[id^="myCarousel"] div:last-child').addClass("active"); 
 });      
});
</script>

Thanks!

Upvotes: 1

Views: 3611

Answers (1)

Elie G&#233;nard
Elie G&#233;nard

Reputation: 1683

Just add the carousel id to your jQuery selector like this:

$(".last").click(function(){
    $('#myCarousel1 div').removeClass('active'); 
    $('#myCarousel1 div:last-child').addClass('active'); 
});

Edit:

If you want the id of your carousel to be dynamic, you have to reference it somewhere. You can put an attribute on the link to the last slide and read this attribute when the link is clicked like this:

$('.last').click(function(e){
    var id = $(this).attr('data-id');
    $('#myCarousel' + id + ' div').removeClass('active'); 
    $('#myCarousel' + id + ' div:last-child').addClass('active');
});

And add a data-id to your link like this:

<li class="last" data-id="2">Last</li>

Upvotes: 2

Related Questions