How to jump to a specific item in Bootstrap's Carousel?

27,097

Solution 1

if your links are in the same order of the panels you can do something like:

$('.link').on('click', function() {
    $('#carousel').carousel($(this).index());
});

if you just have a single link just hardcode it:

var i = 2; //index of the panel    
$('#link').on('click', function() {
    $('#carousel').carousel(i);
});

from the docs:

Methods:

carousel(options)

Initializes the carousel with an optional options object and starts cycling through items.

$('.carousel').carousel({
  interval: 2000
})
.carousel('cycle')

Cycles through the carousel items from left to right.

.carousel('pause')

Stops the carousel from cycling through items.

.carousel(number)

Cycles the carousel to a particular frame (0 based, similar to an array).

.carousel('prev')

Cycles to the previous item.

.carousel('next')

Cycles to the next item.

Solution 2

for me the specified scripted method did not work, however based on another example I was able to make it work using data tags

<a data-target="#myCarousel" data-slide-to="0" href="#">First</a>

Please note that data-slide-to index is based on 0, and this was tested on Bootstrap 4

Share:
27,097
Elijah Yang
Author by

Elijah Yang

Updated on July 10, 2020

Comments

  • Elijah Yang
    Elijah Yang almost 4 years

    Using Bootstrap's Carousel, I want to be able to click on a link and jump to a specific slide in the carousel. How do I do that? What jquery do I have to add?

    Here's my html (it doesn't work but gives you a sense of what I want to do):

    <a href="#panel">Panel</a>
    
    <div id="myCarousel" class="carousel slide">
     <div class="carousel-inner">
      <div id="panel" class="item">
    ...
      </div>
     </div>
    </div>
    
  • Elijah Yang
    Elijah Yang over 11 years
    I tried both methods. I added your jquery to the bootstrap.js file and changing "link" to "panel" but it doesn't work. I also tried putting the <a href="#panel">Panel</a> inside <div id="myCarousel" class="carousel slide" but it still doesn't work.
  • caram
    caram over 4 years
    Excellent, no need for JavaScript, exactly what I was looking for.