Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap Carousel - access current index

How do I get the current index from the carousel?

In this case I am using an unordered list. I know I could search through the list items to find the one with the 'active' CSS class, but I want to know if I can ask the carousel object directly.

Additional: being able to access the target index (on 'slide' event) would be handy also. Again, I can do this by searching with:

var idx = $('.carousel-inner li.active').index();

...and then adding/subtracting based on direction, but I am hoping for something cleaner.

like image 208
Daniel Avatar asked Mar 25 '12 13:03

Daniel


People also ask

How do I change carousel indicators in bootstrap?

You just need to override two properties ( width and height ) and add a new one, border-radius , to . carousel-indicators li . Make width and height values equal eg: 10px each and give a border-radius of 100% . Save this answer.

How do you set a data-interval in carousel?

You can simply use the data-interval attribute of the carousel class. It's default value is set to data-interval="3000" i.e 3seconds. All you need to do is set it to your desired requirements. Save this answer.

How do I display Bootstrap carousel with three posts in each slide?

Following are the steps to create a Bootstrap carousel:Apply CSS to resize the . carousel Bootstrap card body by using the code segment below. In this step, the sliding images are defined in the division tag as under. Last step is to add controls to slide images using the carousel-control class as below.


3 Answers

Instead of adding and subtracting from the current slide, try this on the 'slide' event:

$('.carousel').on('slide',function(e){
    var slideFrom = $(this).find('.active').index();
    var slideTo = $(e.relatedTarget).index();
    console.log(slideFrom+' => '+slideTo);
});
like image 102
Kyle Avatar answered Oct 09 '22 02:10

Kyle


This worked for me (Bootstrap 3)

$("#myCarousel").on('slide.bs.carousel', function(evt) {
  console.debug("slide transition started")
  console.debug('current slide = ', $(this).find('.active').index())
  console.debug('next slide = ', $(evt.relatedTarget).index())
})
like image 39
Dave Sag Avatar answered Oct 09 '22 02:10

Dave Sag


It appears Bootstrap 4 finally has the native implementation of this.

https://github.com/twbs/bootstrap/pull/21668

$('#myCarousel').on('slide.bs.carousel', function(e){
  e.direction     // The direction in which the carousel is sliding (either "left" or "right").
  e.relatedTarget // The DOM element that is being slid into place as the active item.
  e.from          // The index of the current item.     
  e.to            // The index of the next item.
});
like image 19
Quv Avatar answered Oct 09 '22 03:10

Quv