---
slug: "Bootstrapカルーセルの初期アクティブ項目をランダムで選択する"
title: "Randomly Selecting the Initial Active Item in a Bootstrap Carousel"
description: "\n\nThis method allows you to randomly change the initial position when displaying a large carousel in the hero area using Bootstrap."
url: "https://www.ytyng.com/en/blog/Bootstrapカルーセルの初期アクティブ項目をランダムで選択する"
publish_date: "2015-10-27T09:35:57Z"
created: "2015-10-27T09:35:57Z"
updated: "2026-02-27T10:42:51.064Z"
categories: ["Bootstrap"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/d0946a38c86b4f208dd936614ee2e0bf.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Randomly Selecting the Initial Active Item in a Bootstrap Carousel

<div class="document">

<p>This method allows you to randomly change the initial position when displaying a large carousel in the hero area using Bootstrap.</p>
<pre class="literal-block">&lt;div id="hero-carousel" class="carousel slide" data-ride="carousel"&gt;
  &lt;div class="carousel-inner" role="listbox"&gt;
    &lt;div class="item"&gt;
      &lt;img src="..." alt="..." /&gt;
    &lt;/div&gt;
    &lt;div class="item"&gt;
      &lt;img src="..." alt="..." /&gt;
    &lt;/div&gt;
</pre>
<p>Assuming you have a large carousel like this, typically you would set one of the &lt;div class="item"&gt; elements to &lt;div class="item active"&gt;.</p>
<p>To make one active randomly, you can use the following code:</p>
<pre class="literal-block">&lt;script src="js/jquery.min.js"&gt;&lt;/script&gt;
&lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt;

&lt;script&gt;
  $(function () {
    var items = $('.carousel-inner .item');
    var index = Math.floor(Math.random() * items.length);
    items.eq(index).addClass('active');
  });
&lt;/script&gt;
</pre>
<p>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.</p>
</div>
