JuicyBB
JuicyBB

Reputation: 67

Bootstrap carousel with thumbnails (Multiple Carousel)

I was looking up how to create a Bootstrap carousel with thumbnails, and I came across this: http://jsfiddle.net/xuhP9/67/

$('#myCarousel').carousel({
interval: 4000
});

$('[id^=carousel-selector-]').click(function () {
 var id_selector = $(this).attr("id");
 var id = id_selector.substr(id_selector.length - 1);
 id = parseInt(id);
 $('#myCarousel').carousel(id);
 $('[id^=carousel-selector-]').removeClass('selected');
 $(this).addClass('selected');
});

$('#myCarousel').on('slid', function (e) {
 var id = $('.item.active').data('slide-number');
 id = parseInt(id);
 $('[id^=carousel-selector-]').removeClass('selected');
 $('[id^=carousel-selector-' + id + ']').addClass('selected');
});

Which works well, however, I need to have multiple carousel in a page, and I am not quite sure how I can accomplish this. I tired to switch the id selector into a class selector so I can create more than one. But I am not sure how to actually fix the JS functionality to make it work since they seem to be blinded together.

Basically, this is what I am trying to accomplish: http://jsfiddle.net/xuhP9/70/ but without repeating the JS for each independent carousel I create.

Thanks in advance!

Upvotes: 2

Views: 2818

Answers (1)

mildse7en
mildse7en

Reputation: 532

This method requires your carousels to have ID = myCarousel1, myCarousel2 etc.

and your selectors for the corresponding carousel to be carousel-selector1-1, carousel-selector1-2 ... and carousel-selector2-1, carousel-selector2-2

Updated Fiddle: http://jsfiddle.net/xuhP9/77/

$('.customCarousel').carousel({
     interval: 4000
 });

 // handles the carousel thumbnails
 $('[id^=carousel-selector]').click(function () {
     var id_selector = $(this).attr("id");
     var id = id_selector.substr(id_selector.length - 1);
     id = parseInt(id);
     var parent = $(this).closest('ul').data('carousel');
     $('#myCarousel' + parent).carousel(id);
     $('[id^=carousel-selector' + parent +'-]').removeClass('selected');
     $(this).addClass('selected');
 });

 // when the carousel slides, auto update
 $('.customCarousel').on('slid', function (e) {
     var cont = $(this).data('carousel');
     var id = $('#myCarousel'+ cont +' .item.active').data('slide-number');
     id = parseInt(id);
     $('[id^=carousel-selector' +cont+'-]').removeClass('selected');
     $('[id^=carousel-selector'+cont+'-' + id + ']').addClass('selected');
 });

Upvotes: 3

Related Questions