Meeps Meeps - 6 months ago 20
Javascript Question

How to target bootstrap carousel's active slide?

Evening,

Apologies for this likely being a really stupid question, I'm still learning!

I'm trying to target the active slide in the bootstrap carousel to perform an action. I'd like it to trigger some style changes for each of the three slides i.e. changing button colours etc.

Earlier I tried just targeting the divs by their numbers(

#1, #2, #3
), but kept getting stuck there too, it looked something like this;

var shead = document.getElementById("sub-head");
if ($('#1').is(':visible') && $('#2').is(':hidden') && $('#3').is(':hidden')) {
shead.style.color = "blue";
}


I repeated this for each of the slides using
:visible
&
:hidden
for each of the divs accordingly, although I only ever seemed to get stuck with the last presentation of the style colour change.

I did a some searching on this and I've seen people using
.carousel(1)
, but I just seem to keep hitting dead ends, can anyone give me a hand with this, not sure why it's not catching, any guidance would be appreciated?

HTML

<header id="Carousel" class="carousel slide carousel-fade">

<ol class="carousel-indicators">
<li data-target="Carousel" data-slide-to="0" class="active"></li>
<li data-target="Carousel" data-slide-to="1"></li>
<li data-target="Carousel" data-slide-to="2"></li>
</ol>

<div class="carousel-inner">
<div class="item active" id="1"></div>
<div class="item" id="2"></div>
<div class="item" id="3"></div>
</div>

</header>


JAVASCRIPT

if ($('#Carousel').carousel(1).hasClass('active')) {
alert("this is an alert");
}

Answer

Bootstrap has custom events you can hook to.

This event will fire when the method is going to slide.

$('#Carousel').on('slide.bs.carousel', function (ev) {
  var id = ev.relatedTarget.id;
  switch (id) {
    case "1":
      // do something the id is 1
      break;
    case "2":
      // do something the id is 2
      break;
    case "3":
      // do something the id is 3
      break;
    default:
      //the id is none of the above
  }
})

There is also a slid.bs.carousel event. This event is invoked when the slider is finished sliding.

You can read about the differences here http://getbootstrap.com/javascript/#carousel-events.

Comments