Randomly Selecting the Initial Active Item in a Bootstrap Carousel

Bootstrap
2015-10-27 18:35 (9 years ago) ytyng

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.

Current rating: 2
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011