Cymro
Cymro

Reputation: 1291

Bootstrap 5 Carousel will not autoplay after page load

This standard Bootstrap 5 carousel code...

<div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="1.jpg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="2.jpg" class="d-block w-100" alt="...">
</div>
</div>
</div>

...auto plays when it is in the html file when the page is loading.

When, however, the same code is added to the DOM after page load with:

$('#previous-div').after(carouselHTML);

...the carousel does not autoplay.

What steps do I need to take to have the carousel auto play, when the carousel is added to the DOM after page load?

Upvotes: 1

Views: 102

Answers (2)

Cymro
Cymro

Reputation: 1291

I finally got it to work with this code:

<script>
var myCarousel = document.querySelector('#carousel-id')
var carousel = new bootstrap.Carousel(myCarousel, {interval:2000,wrap:false})
</script>

Upvotes: 0

traynor
traynor

Reputation: 8717

As per docs, Carousel components with data-bs attribute are initialized automatically on page load, so adding them later won't work.

So, you can instantiate it manually with JavaScript.

You seem to be using jQuery, so BS components are automatically available, so you can instantiate carousel by passing cycle to .carousel method:

 $('#previous-div').after($(carouselHTML).carousel('cycle'));

demo:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <title>Bootstrap Example</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>


  <div id="previous-div"></div>


  <script>
    $(document).ready(function() {

      const carouselHTML = `
      <div id="carouselExampleSlidesOnly" class="carousel slide">
      <div class="carousel-inner">
      <div class="carousel-item active">
      <img src="https://placehold.co/300x200" class="d-block w-100" alt="...">
      </div>
      <div class="carousel-item">
      <img src="https://placehold.co/300x200" class="d-block w-100" alt="...">
      </div>
      </div>
      </div>
  `;


      $('#previous-div').delay(2000).after($(carouselHTML).carousel('cycle'));



    });
  </script>

</body>

</html>

Upvotes: 0

Related Questions