jqueryjsonajaxtwitter-bootstrapbootstrap-carousel

Adding active class in Carousel Bootstrap Ajax Jquery


I have this set of code which mange to call the image dynamically from database (data reference table)

HTML Carousel:

  <!--- Carousel Slider --->
   <div class="col-lg-8 col-md-12">
     <div class="text-center mb-50">
       <div class="card" style="border: none;">
         <div class="">
            <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
              <div class="carousel-inner" id="carousel"></div>
                 <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
                  <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                   <span class="sr-only">Previous</span>
                 </a>
                 <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
                  <span class="carousel-control-next-icon" aria-hidden="true"></span>
                   <span class="sr-only">Next</span>
                 </a>
              </div>
             </div>
          </div>
       </div>
      </div>

Jquery code:

$(document).ready(function() {
// display carousel
$.getJSON("/datas/json?id=8&q=status_carousel%:%Show", function(data) {
    $("#carousel").html('');
    var carousel_output = "";

    $.each(data, function () {
        carousel_output +=  "<div class='carousel-item'><img class='d-block w-100' src='"+ this.value +"'></div>";
    });
  
    $("#carousel").append(carousel_output);
   });
});

However, it still do not show the image that was called using the script above. I have tried few ways of adding the active class in the code but to my dissapointment, they didnt work. Appreciate any help from you guys.


Solution

  • Try this:

    $(document).ready(function () {
        // display carousel
        $.getJSON("/datas/json?id=8&q=status_carousel%:%Show", function (data) {
            var carousel_output = "";
            $.each(data, function () {
                carousel_output += "<div class='carousel-item'><img class='d-block w-100' src='" + this.value + "'></div>";
            });
            $("#carousel").html(carousel_output);
            $("#carousel").find('.carousel-item:first-child').addClass('active');
        });
    });