---
slug: "Bootstrapカルーセルの初期アクティブ項目をランダムで選択する"
title: "Bootstrapカルーセルの初期アクティブ項目をランダムで選択する"
description: "\n\n\nBootstrap で、ヒーローエリアの大カルーセルを表示する時、初期位置をランダムで変更する方法です。"
url: "https://www.ytyng.com/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: "ja"
---

# Bootstrapカルーセルの初期アクティブ項目をランダムで選択する

<div class="document">


<p>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>このような大カルーセルがあるとして、通常は どれか1つの &lt;div class="item"&gt; を &lt;div class="item active"&gt; にしておくものと思います。</p>
<p>ランダムで active にするには</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>こんな感じで、Jquery で1つを選択し、addClass すると良いでしょう。</p>
<p>bootstrap.js の読み込み後でも動作します。賢い。</p>
</div>
