On my webpage, there are several bootstrap 5.3 carousels that I want to start with a delay. The plan is for each carousel to begin at different intervals – the first one after 1 second, the second after 2 seconds, the third after 3 seconds, and so forth.
Every carousel is uniquely identified with an id
, for example:
<div class="card-image">
<div id="carousel__<?php echo $row['guid']; ?>" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<a href="<?php echo $galleryLink; ?>">
<img class="img-card-gallery" src="<?php print $coverPhoto . '?t=' . time(); ?>" alt="">
</a>
</div>
<?php
for ($i = 0; $i < count($imgfileNames); $i++) {
echo '
<div class="carousel-item">
<a href="' . $galleryLink . '">
<img class="img-card-gallery" src="' . $imgfileNames[$i] . '?t=' . time() . '" alt="' . $imgartTitles[$i] . '">
</a>
<div class="carousel-caption d-none d-md-block">
<!-- Here you can add Caption -->
</div>
</div>
';
}
?>
</div>
</div>
<!-- <a href="<?php echo $galleryLink; ?>"><span class="<?php if($galleryTitle=='') echo 'card-title-without-text'; else echo 'card-title-with-text'; ?>"><?php echo $galleryTitle ?></span></a>-->
</div>
Unfortunately, my JavaScript code is not functioning as expected, as all the carousels start simultaneously. Here is the problematic snippet:
<script>
$(document).ready(function() {
var carousels = $('.carousel-fade');
var initialInterval = 1000;
carousels.each(function(index, carousel) {
var carouselInstance = new bootstrap.Carousel(carousel, { interval: 0 });
console.log('Setting the carousel number ' + index + ' with an interval of ' + initialInterval + 'ms');
setTimeout(function() {
carouselInstance.interval = initialInterval;
carouselInstance.cycle();
}, 1000);
initialInterval += 1000;
});
});
</script>