Add slides to Bootstrap 3 carousel dynamically using jQuery

56,614

Solution 1

First thing, I will rely on the fact that m is an array with proper url to your images.

The HTML should be like this:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
  <ol class="carousel-indicators"></ol>
  <!-- Wrapper for slides -->
  <div class="carousel-inner"></div>
  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
  </a>
</div>

Class carousel inner is empty, there is where you gonna place your images for then carousel.

Class carousel-indicatiors is also empty, will be filled by JS.

Then, comes the JS: (as I said, Im relying on the fact that m is an array of imgs url)

$(document).ready(function(){  
  for(var i=0 ; i< m.length ; i++) {
    $('<div class="item"><img src="'+m[i]+'"><div class="carousel-caption"></div>   </div>').appendTo('.carousel-inner');
    $('<li data-target="#carousel-example-generic" data-slide-to="'+i+'"></li>').appendTo('.carousel-indicators')

  }
  $('.item').first().addClass('active');
  $('.carousel-indicators > li').first().addClass('active');
  $('#carousel-example-generic').carousel();
});

Basically, you append all your images to class carousel-inner, you add carousel control li's, then you add the active class to the first image and to the first carousel indicator li., and finally, you initialize your carousel. Note that all this is inside a document ready function, which is what you are missing. What you do is only define a function called onload

Hope it helps !

EDIT: I saw that you are outputting also alt tag to images, but thats something that not need to be on my answer, I bet you can do that without problems.

Solution 2

Here is a more current answer. The solution by @avcajaraville was written in 2014; with Bootstrap version 4 the concepts he presented are still applicable but the details regarding Class names have changed and the old code won't work.

In this solution, I don't bother with "indicators," the addition of indicators is left to the interested reader. (The "indicators" are symbols representing the list, there is one "dot" per photo in the carousel, and the dot for the current photo is highlighted.)

Here is the HTML. This is "bare-bones" version. A more robust version appears later in this post.

<div id="myCarousel" class="carousel slide" >
    <div class="carousel-inner" role="listbox">
    </div> 
</div>

Note that I left out the attribute data-ride="carousel"; the equivalent is expressed in the config options passed via JavaScript. This complies with the latest documentation.

Here is the JavaScript. For the sake of variety, this code differs from that of @avcajarville by mostly not using jQuery. On the other hand, the interface to Bootstrap is through jQuery, only, and that is what you see in the last line of this code.

The presumption is that an array called recs is a list of objects, where each object holds information about the photos, including the file name and some descriptive text. For each rec, a string of html is generated, and pushed onto the array itemHtmlStrings. Those strings then become the innerHTML of carousel-inner element. Then, one of the new elements (the first one) gets marked as the active (i.e. visible) image.

var itemHtmlStrings = [];
for(var rec of recs) {
  var itemHtmlString = ''
    +'<div class="carousel-item">'
    + `<img class="d-block w-100" `
    +       ` src="photo/${rec.name}" alt="photo of ${rec.name}">`
    +  `<div class="carousel-caption">`
    +    `<h3>${rec.captionHdr}</h3>`
    +    `<p>${rec.captionText}</p>`
    +  '</div>'
    +'</div>'
  itemHtmlStrings.push(itemHtmlString);
}
var myCarouselEl = document.getElementById("myCarousel");
var carouselInnerEl = myCarouselEl.getElementsByClassName("carousel-inner")[0];
carouselInnerEl.innerHTML = itemHtmlStrings.join("\n");
carouselInnerEl.firstElementChild.className += " active";
$(myCarouselEl).carousel({slide : true, ride : true });

Unfortunately, after writing this code, I decided that the Carousel offered by Bootstrap is not for me. This code is OK if your only requirement is to rotate through an enumerated set of images and show exactly one at a time. I am not using this code because I need to show more than one image, and it seems Bootstrap does not do that. Furthermore, I had problems because my images are not all identical; some needed to be rotated upon load; that was a problem in Bootstrap Carousel. Also, I'm not sure how well it handles diversity of size and aspect ratio.

I promised the non-bare-bones version of the HTML, so here it is. This includes buttons that allow the user to request the Previous and Next slide. Also, it includes aria-hidden attributes and sr-only spans; these are codes for screen readers. The sr-only class is the Bootstrap indicator of screen-reader-only. (Screen reader is a "voice" for visual impaired people.)

<div id="myCarousel" class="carousel slide" >
    <div class="carousel-inner" role="listbox">
    </div>
    <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true" style="background-color:black; color:white;"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true" style="background-color:black; color:white; font-size=x-large"></span>
        <span class="sr-only">Next</span>
    </a>
</div>

To add indicators, put <ol class="carousel-indicators"></ol> prior to the carousel-inner, and adjust the JavaScript code to insert a list of <li> elements. When using indicators, you will need to set "active" on the appropriate (i.e. first) indicator element, as was done by @avcajaraville.

Good luck, and have fun.

Solution 3

You can give this a try.

Markup

<div id="carousel-deck" class="carousel slide" data-ride="carousel"
    data-interval="false" data-wrap="false">
    <ol class="carousel-indicators">
    </ol>
    <div class="carousel-inner">
    </div>
    <a class="left carousel-control" href="#carousel-deck"
        data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span><span
            class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#carousel-deck"
        data-slide="next"><span
            class="glyphicon glyphicon-chevron-right"></span><span
            class="sr-only">Next</span>
    </a>
</div>

JS

var markup = '';
for (var index = 0; index < count; index++) {
    markup += '<li data-target="#carousel-deck" data-slide-to="' + index + '"></li>';
}
$('#carousel-deck .carousel-indicators').html(markup);
markup = '';
for (var index = 0; index < count; index++) {
    markup += '<div class="item">';
    markup += '<img src="/images/uploads/' + file.uuid + '/slides/slide_' + (index + 1) + '.jpg" style="width:100%;">'
    markup += '</div>';
}
$('#carousel-deck .carousel-inner').html(markup);
$('#carousel-deck .item').first().addClass('active');
$('#carousel-deck .carousel-indicators > li').first().addClass('active');
$('#carousel-deck').carousel({
    pause: true,
    interval: false
});
Share:
56,614

Related videos on Youtube

idrisjafer
Author by

idrisjafer

Updated on July 09, 2022

Comments

  • idrisjafer
    idrisjafer almost 2 years

    I'm trying to add slides to Bootstrap carousel using jQuery but it is not acting as a slider in the browser. Instead it's showing the images in list view.

    <!DOCTYPE html>
    <html>
    <head>
    <link href="Assets/css/bootstrap.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">        </script>
    <script src="Assets/js/bootstrap.min.js"></script>
    <title></title>
    <script>
        onload=function(){
    
            for(var m=3;m>=0;m--)
            {
                var path="file_uploads/"+m+".jpg";
                $(".carousel-indicators").after("<li data-target='#carousel-example-generic' data-slide-to=\""+m+"\"></li>");
                $(".carousel-inner").after("<div class='item'><img src='"+path+"' alt='"+m+"'></div>");             
            }
    
            $(".carousel-indicators li:first").addClass("active");
            $(".carousel-inner .item:first").addClass("active");
            $('.carousel').carousel();
        }
    </script>
    </head>
    <body>
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
        <ol class="carousel-indicators">
    
        </ol>
        <!-- Wrapper for slides -->
        <div class="carousel-inner">       
    
        </div>
    
        <!-- Controls -->
        <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
        </a>
        <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
        </a>
      </div>
    </body>
    </html> 
    
  • IAM_AL_X
    IAM_AL_X over 4 years
    Warning: For Bootstrap version 4, there are changes. Several classes are different in v3 versus v4, and the code is not interchangeable. The concepts are the same, but class names are different.
  • IAM_AL_X
    IAM_AL_X over 4 years
    The class names have changed for version 4. Your code should be preserved, since some people are still using version 3. See also my post, below.