I'm trying to click a button that pauses a Bootstrap 5 carousel.
The pause is not working.
I have a Code Pen Example and repeated the code below as well.
document.getElementById("btnPause").addEventListener("click", function () {
var carouselElement = document.getElementById("carouselAnimals");
var carousel = new bootstrap.Carousel(carouselElement);
carousel.pause(); // seems to get called, but doesn't pause
// carousel('pause'); // doesn't work
// carousel.carousel('pause'); // doesn't work
});
<div class='container'>
<div class="container">
<div class="row">
<div class="col-3">
<button id='btnPause' class="btn btn-secondary">Stop carousel</button>
</div>
<div class="col">
<div id="carouselAnimals" class="carousel slide" data-bs-ride="carousel" data-bs-interval='1000' data-interval='100' >
<div class="carousel-inner">
<div class="carousel-item active">
<img src="https://placekitten.com/800/500" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="https://loremflickr.com/800/500" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="http://placeimg.com/800/500/animals" class="d-block w-100" alt="...">
</div>
</div>
</div>
</div>
</div>
</div>
I guess the way you are trying to do results in two different carousel instances.
But the second one is not rendered anywhere.
So in order to make it stop, initialise it yourself before pressing the button like so:
var carouselElement = document.getElementById("carouselAnimals");
/* it looks like manually initialising the carousel
will overwrite html data-attributes, so you have to
specify properties when creating the slider */
var carousel = new bootstrap.Carousel(carouselElement, {
interval: 100
});
document.getElementById("btnPause").addEventListener("click", function () {
carousel.pause();
});
Working example (JSFiddle, sorry don't have a codepen account): https://jsfiddle.net/y5z98xfe/