Creating JavaScript Sliders Using Twitter Bootstrap 3

Syed Fazle Rahman

Twitter Bootstrap 3 is one of the best CSS frameworks for developing and designing content management systems. It is easy to design blogs, portfolios and profiles using Twitter Bootstrap’s grid layouts. One thing that many types of CMS have in common is the “Slider”. A sequential automated display of images, a slider can be anything: showcasing your latest projects, showing off your client’s assets, describing special offers, linking to news items, or highlighting your latest blog posts.

In this article, we will learn how to create a JavaScript slider using Twitter Bootstrap 3’s Carousel Component.

Understanding Twitter Bootstrap 3 Carousel Component

The markup for the Carousel Component goes as follows:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">

  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

  <!-- Slider Content (Wrapper for slides )-->
  <div class="carousel-inner">
    <div class="item active">
      <img src="..." alt="...">
      <div class="carousel-caption">
        ...
      </div>
    </div>
    ...
  </div>

  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
  </a>
</div>

From the above code, we understand that Bootstrap 3 carousel is divided into three major sections:

  1. Indicators
  2. Slider content
  3. Controls

See the live demo of the slider created using the default Bootstrap 3 structure.

To set any div as the slider, we have to apply the classes carousel and slide. The carousel class defines the element as an element with a “merry-go-round” feature. The slide is applied to add the slide effect when the slider changes.

Indicators are the small circles placed at the bottom center of the slider to indicate the current slide position and the number of sliders in total. Indicators are declared using an ordered list.

<ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

The ordered list is given the class carousel-indicators to make the child elements look like small circles. Each li element must have a data-target attribute with the value as the id of the parent carousel div. They must also have a unique data-slide-to attribute with integer values as strings in an incremental order starting from “0”.

Slider content is the main portion of the slider. It is in this space we will place our slider’s content. The slider content area is defined using the class carousel-inner. This div can again have unlimited item divs. The first item div must have an active class defined.

<div class="carousel-inner">
    <div class="item active">
      <img src="..." alt="...">
      <div class="carousel-caption">
        ...
      </div>
    </div>
    ...
  </div>

Each item div has two subsections: image and carousel-caption. The image is used as full width display content in the slider. The carousel-caption is placed floating over its respective image. You can place either an <h3></h3> element or a <p></p> element – or even both – inside the carousel-caption.

Controls are the left and right arrow marks that are used to manually change the slider.

<!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
  </a>
</div>

There should be two elements: one for each arrow. The first element will have a span with the glyphicon glyphicon-chevron-left class to show the left arrow, and the second element will have glyphicon glyphicon-chevron-right to show the right arrow. Since Bootstrap uses fonts instead of images to show the icons, we have to follow glyphicon classes to show the icons.

That’s it! You have successfully created a slider for your website. Plus, we didn’t write a single line of JavaScript to make it work. bootstrap.js does things automatically for you.

Carousel Options

You can further customize the default functions of the slider by adding some more data-* attributes to the parent carousel div.

data-interval is used to indicate the time gap between each slide. It takes a number as the value and the number represents milliseconds.

data-pause is used to define when to pause the sliding activity. If the value is “hover” it stops sliding when the mouse is placed on the slider.

data-wrap is a boolean attribute which tells whether or not the slider should continue sliding from the beginning once the end is reached.

For JQuery Geeks

Well, if you love using jQuery and data-* attributes are not your cup of tea, then Bootstrap allows you to initialize sliders using JavaScript, too!

To make a carousel div work like a carousel, you have to write the following snippet:

$('.carousel').carousel()

The Carousel options can then be set by passing a JSON object inside the carousel function.

For example:

$('.carousel').carousel({
  interval: 2000,
  pause: “hover”,
    wrap: true
})

You can also manually trigger slider events using snippets like the ones below:

.carousel('pause') // to pause the slider
.carousel('cycle') // to cycle through the slider items
.carousel(2) // to forcibly display the the 3rd slide in the slider
.carousel('prev') // to show the previous slide
.carousel(‘next’) // to show the next slide in the slider

The above methods may be called from within any JavaScript code to manipulate the normal working of the slider. I do find the prev and next methods very useful when I want to display my own buttons instead of Bootstrap’s arrows. Especially when they are placed outside the carousel’s parent div.

Conclusion

Hopefully, you have enjoyed learning how to create JavaScript sliders without writing thousands of lines of JavaScript code.

I think, when used properly, Twitter Bootstrap’s JavaScript Components will prove to be an essential part of your development process.

They will surely save you the most development time. Most importantly, they are cross browser compatible, so you don’t have to tear your hair out in order to make them work in older browsers.

Visit the Demo Page.

Read more about Twitter Bootstrap’s JavaScript Components.

If you are new to it, you can start learning Twitter Bootstrap here.

If you have any suggestions or feedback on this article, do mention them below in the comments section. I will be happy to hear them and help where I can.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • John T.

    Awesome.. :D thanks for explaining so clearly..

  • Keith Jones

    Nice work – thank you.

  • girlwithglasses

    It’s worth checking out the usability concerns of employing a carousel or slider on your website; there are a number of issues, including only the first image being seen; people skipping past the content as they dismiss it as an ad; user frustration at being unable to control the carousel; and so on. There’s a recent article on the Nielsen Norman group site about them: http://www.nngroup.com/articles/designing-effective-carousels/

  • Glow

    I don’t see the benefit of bootstrap here, basic jquery carousel with ugly html markup

  • Sudipta Banerjee

    Can we create carousel effect as used in http://test.t2india.us/ (Destinations Section [Bottom of Page]) using Bootstrap. Idea is to have multiple items per cycle.

    Any help is appreciated..

  • Anonymous

    Thank you for the nice article!
    May I ask how can I style the little navigation buttons (indicator) in the middle? Say move to top right, and change the color & shape?

  • Zin Min Tun

    ႊThank you. Very good tutorial for me.

  • mydove angel

    Nice article please how can i be updating or change the image from cms. Thanks

  • Bombozama

    I been working on figuring out how to best handle outside controls for the carousel with data attributes. I think this could help someone in the future:

    – Add a link anywhere outside of the carousel container.
    – make sure the href of the link points to the id selector of the carousel container ( href=”#carousel-example-generic” )
    – add data-slide-to=”SLIDENUMBER” or data-slide=”prev” or data-slide=”next” to the link

    You are now ready to go.