0

I've few images which I'm trying to add in a loop to the bootstrap 4 carousel. I tried with the below code which doesn't seem to work. However if I add the same items manually (with the same HTML snippet from jQuery) for all items, it's working.

<body>
  <div class="container-fluid px-0">
    <div class="header">
        <span>Some Header<span>
    </div>
    <div id="myImage" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner bg-info" role="listbox">
            
        </div>
        <a class="carousel-control-prev" href="#myImage" 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="#myImage" role="button" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

  <script>
    $(document).ready(function(){
      var totalItems = 3;
      for(var i = 1 ; i <= totalItems ; i++) {
        $('<div class="carousel-item"><div class="d-flex align-items-center justify-content-center min-vh-100"><img src="img/myimg'+i+'.jpg"></div></div>').appendTo('.carousel-inner');
        
      }
      $('.carousel-item').first().addClass('active');
      
      $('.carousel').carousel({
        interval: false,
      });
    });
    
  </script>
</body>

I followed the answer mentioned here.

For easier purpose I've created fiddle with the above code here. However In this fiddle, I'm taking an array and adding from the array as the uploaded images have random URL. And surprisingly this works.

In the original code I've the image path available and hence not using an array. I'm using the image path with the number from the loop as mentioned above.

Can anybody point me what am I doing wrong here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
RatDon
  • 3,403
  • 8
  • 43
  • 85

1 Answers1

0

Actually everything looks fine, maybe there might be an error in the image path or img ext, if the img folder is in root, try this; "<img src = "/img ..."

Murat Kezli
  • 187
  • 2
  • 5