Randomly Selecting the Initial Active Item in a Bootstrap Carousel
Bootstrap
2015-10-27 09:35 (10 years ago)

This method allows you to randomly change the initial position when displaying a large carousel in the hero area using Bootstrap.
<div id="hero-carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="item">
<img src="..." alt="..." />
</div>
<div class="item">
<img src="..." alt="..." />
</div>
Assuming you have a large carousel like this, typically you would set one of the <div class="item"> elements to <div class="item active">.
To make one active randomly, you can use the following code:
<script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script><script> $(function () { var items = $('.carousel-inner .item'); var index = Math.floor(Math.random() * items.length); items.eq(index).addClass('active'); }); </script>
With this approach, you can use jQuery to select one item and add the 'active' class to it. This will work even after loading bootstrap.js. Clever.
Please rate this article
Current rating: 2.0 (1)
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.