Bootstrap Carousel with dynamic items does not slide

Andre Zimpel picture Andre Zimpel · Sep 26, 2013 · Viewed 34.5k times · Source

I'm using the stock bootstrap carousel:

<div id="main-navigation-carousel" class="carousel slide">
  <div class="carousel-inner">
    <div class="item active" data-id="0">
      <ul>
        <li><a></a></li>
        ....
        <li><a></a></li>
      </ul>
    </div>
  </div>
</div>

By clicking on an anchor tag inside the carousel a new .item is injected to the .carousel-inner. After the .item is injected (which works fine) the carousel should slide to that .item. However, nothing happens.

<div id="main-navigation-carousel" class="carousel slide">
  <div class="carousel-inner">
    <div class="item active" data-id="0">
      <ul>
        <li><a></a></li>
        ....
        <li><a></a></li>
      </ul>
    </div>
    <div class="item" data-id="1">
      <ul>
        <li><a></a></li>
        ....
        <li><a></a></li>
      </ul>
    </div>
    <div class="item" data-id="2">
      <ul>
        <li><a></a></li>
        ....
        <li><a></a></li>
      </ul>
    </div>
  </div>
</div>

Even if I use $("#main-navigation-carousel").carousel(1); in the browser console nothing happens. If I add items right in the code on the server everything works fine.

Answer

Andre Zimpel picture Andre Zimpel · Sep 26, 2013

Removing the carousel data and then triggering it again does the job!

$("#main-navigation-carousel").carousel("pause").removeData();
$("#main-navigation-carousel").carousel(target_slide_index);

Since the carousel should not auto slide it is important to use .carousel("pause").removeData().