Auto-Generate Twitter Bootstap Carousel Indicators
I've recently had the privilege of setting up Bootstrap carousel within a content management system so a less technical user could add, edit and remove slides without worrying much about the HTML. On that note, it made sense to me that the carousel be smart enough to automatically add the carousel indicator dots, depending on how many items are in the carousel. I found that the following bit of jQuery before invoking the carousel works wonders.
First, I omitted the "carousel-indicators" ordered list from Bootstrap’s boilerplate HTML, entirely. (Afterall, I want that to self-generate when the page is rendered.) Presuming the rest of the HTML is in place, here’s what to add to your script before calling the carousel:
<!-- auto-generate carousel indicator html -->
var myCarousel = $(".carousel");
myCarousel.append("<ol class='carousel-indicators'></ol>");
var indicators = $(".carousel-indicators");
myCarousel.find(".carousel-inner").children(".item").each(function(index) {
(index === 0) ?
indicators.append("<li data-target='#myCarousel' data-slide-to='"+index+"' class='active'></li>") :
indicators.append("<li data-target='#myCarousel' data-slide-to='"+index+"'></li>");
});
<!-- then call carousel -->
$('.carousel').carousel();
Written by Eddie Staples
Related protips
6 Responses
Cool, its really helpful, so simple but for a Crown...
Really nice!
hi
nice solution but:
How will you do that if you have two bootstrap carousels on your page???
I tried and even if i change names to target each Carousel separetely to generate it, one of my carousel echo the ol li indicators of the other one
This is truly awesome!! I found this over 2 years after it was published and I'm really glad. I'm doing a Web Dev course and had this type of problem to solve and this coder here made my day!! Thanks so much!! Now I need to sit down and understand what the code is really doing bit by bit. Thanks again!!
I wish I'd found this 4 hours ago! Thank you so much.
Very helpful, thank you!