Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Bootstrap Carousel's carousel-indicators

What's wrong with my code? I want to trigger the current bootstrap carousel slide number. I want to change a text or do some jQuery command when a specific slide. Please see my code.

$(document).ready(function() {

$('#myCarousel').on('slide.bs.carousel', function (ev) {
  var id = ev.relatedTarget.id;
  switch (id) {
    case "1":
      $('#sometext').text("one");
      break;
    case "2":
      $('#sometext').text("two");
      break;
    case "3":
      $('#sometext').text("three");
    default:
      //the id is none of the above
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>


<h1 id="sometext">Some Text here</h1>


<div id="myCarousel" class="carousel slide" data-ride="carousel">


    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="http://www.w3schools.com/bootstrap/img_chania.jpg" alt="Chania" width="460" height="345">
      </div>

      <div class="item">
        <img src="http://www.w3schools.com/bootstrap/img_chania2.jpg" alt="Chania" width="460" height="345">
      </div>
    
      <div class="item">
        <img src="http://www.w3schools.com/bootstrap/img_flower.jpg" alt="Flower" width="460" height="345">
      </div>

      <div class="item">
        <img src="http://www.w3schools.com/bootstrap/img_flower2.jpg" alt="Flower" width="460" height="345">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
like image 341
LayoutPH Avatar asked Oct 19 '22 10:10

LayoutPH


1 Answers

Try

$(document).ready(function() {    
   $('#myCarousel').on('slide.bs.carousel', function (ev) {
       var idx = $(ev.relatedTarget).index() + 1;
       console.log(idx);
   });
})
like image 144
tmg Avatar answered Nov 01 '22 14:11

tmg