AAA
AAA

Reputation: 2032

Firing events in Twitter Bootstrap's Carousel

Once the carousel has slid, I want to add a value to an input outside of the ID myCarousel.

The function to implement an event once the carousel has slid is this:

$('#myCarousel').bind('slid', function() {
  $('input[name=linkOnly]').val('Test')
}

I want to fire an event once a particular slide slides. I've tried something like $('#myCarousel li[data-slide-to=1]').bind('slid', function() ... but it doesn't register.

Any help appreciated, thanks.

Upvotes: 2

Views: 3100

Answers (1)

zkcro
zkcro

Reputation: 4344

You could just setup an event handler on the appropriate event and then choose to do anything based on which slide is .current. For example, to trigger some javascript when slide 1 cycles in:

$(document).on("slid", function(event) {
  if ($(event.target).find(".active").data("slide-to") == 1) {
    // do stuff
  }
});

From a quick test, this doesn't seem to work unless it attached to an element above the carousel (you'd also need to change things a little if you had more than one carousel).

EDIT: After a quick look, the reason the above doesn't work if bound to the carousel itself is that the active class isn't added until immediately after the slid event is triggered (it seems that if the handler is added to a parent element, the active class gets added while the slid event bubbles up). You can get around this by using setTimeout to delay the triggered behaviour (works even with a timeout of 0):

$("#myCarousel").on("slid", function(event) {
  var carousel = $(event.target);
  setTimeout(function() {
    if (carousel.find(".carousel-indicators .active").data("slide-to") === 1) {
      // do stuff
    }
  }, 0);
});

Whether the extra code is worth it is up to you, although it may be a little more stable. It may even be worth putting in a small delay (instead of 0), just to make sure that things do work the way you expect them to.

Upvotes: 4

Related Questions