Try Tuts+ Premium, Get Cash Back!
Twitter Bootstrap 101: The Carousel
videos

Twitter Bootstrap 101: The Carousel

Tutorial Details
  • Topic: Twitter Bootstrap, Carousel
  • Difficulty: Beginner
  • Estimated completion time: 30 mins
This entry is part 6 of 8 in the series Twitter Bootstrap 101

One of Twitter Bootstrap’s many handy features is a pleasing sliding carousel for featuring images and content! Setup is not difficult. It requires some structured markup, the Bootstrap jQuery plugin, and a couple of lines of JavaScript to initialize it. Let me show you how it’s done!


The Screencast

Alternatively, Download the video, or subscribe to Webdesigntuts+ screencasts via iTunes or YouTube!

For those of you who appreciate tutorials in black and white, let’s go over:

  1. The Carousel Markup
  2. The Carousel JavaScript
  3. Adjusting Carousel Settings
  4. Supplying your own Content and Captions


Step 1: The Carousel Markup

The Bootstrap carousel requires a specific markup pattern, with appropriate classes.

Carousel and Carousel-inner

<!--  Carousel - consult the Twitter Bootstrap docs at
      http://twitter.github.com/bootstrap/javascript.html#carousel -->
<div id="this-carousel-id" class="carousel slide"><!-- class of slide for animation -->
  <div class="carousel-inner">
    <div class="item active"><!-- class of active since it's the first item -->
      <img src="http://placehold.it/1200x480" alt="" />
      <div class="carousel-caption">
        <p>Caption text here</p>
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/1200x480" alt="" />
      <div class="carousel-caption">
        <p>Caption text here</p>
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/1200x480" alt="" />
      <div class="carousel-caption">
        <p>Caption text here</p>
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/1200x480" alt="" />
      <div class="carousel-caption">
        <p>Caption text here</p>
      </div>
    </div>
  </div><!-- /.carousel-inner -->
  <!--  Next and Previous controls below
        href values must reference the id for this carousel -->
    <a class="carousel-control left" href="#this-carousel-id" data-slide="prev">&lsaquo;</a>
    <a class="carousel-control right" href="#this-carousel-id" data-slide="next">&rsaquo;</a>
</div><!-- /.carousel -->

Once we’ve supplied the markup, we need to initialize the carousel JavaScript to do its work on this carousel.


Step 2: The Carousel JavaScript

Let’s begin by making sure the necessary JavaScript is connected to this page. You’ll find your JavaScript links near the bottom of the page, near the closing body tag.

jQuery

The best, most highly recommended way to link jQuery is to link to a CDN-hosted version. This provides a speedier download, and it may already be cached in your user’s browser.

But of course it would be nice to have a fallback, so that if something happens to that CDN-hosted version, the user can get it locally from your own site files. That is exactly what the good folks at the HTML5 Boilerplate recommend, and it looks like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.7.2.min.js"><\/script>')</script>

Note that the first line reaches out to Google’s hosted version. The second line uses JavaScript to check that the first line did its job. If not, it auto-generates a link to your own hosted copy of jQuery, which you’ve included in your own site files (as I have here).

Bootstrap’s jQuery Plugins

Once we’ve linked jQuery, we need Bootstrap’s jQuery plugins. I’ve included the complete compiled and minified version of all of Bootstrap’s plugins. Thus my link looks like this:

<script src="js/bootstrap.min.js"></script>

Initialize the Carousel

Once we’ve provided jQuery plus Bootstrap’s plugins, we just need to initialize the Carousel plugin to do its work on our carousel.

<script>
  $(document).ready(function(){
    $('.carousel').carousel();
  });
</script>

In plain English, this means: Once the HTML document is ready, identify the element(s) with a class of "carousel", and direct the carousel plugin to do its thing to it.

Refresh and Check

Once the markup is in place, and the JavaScript has been supplied correctly, you should be able to refresh your browser and see the results. Each image rotation takes five seconds. Be sure that your mouse does not hover over the slideshow, as this pauses its timer.


Step 3: Adjust Settings as Desired

You can add parameters to adjust the time between the carousel sliding behavior.

For example, you could change the timing to 2-second (2,000 millisecond) intervals as follows:

<script>
  $(document).ready(function(){
    $('.carousel').carousel({
      interval: 2000
    });
  });
</script>

Step 4: Your Own Content and Captions

In the markup for Step 1, above, I’ve used Placehold.it images. Note that images of 1200 pixels wide are large enough to stretch the full maximum width of the standard Bootstrap responsive site. I’ve used a ratio of 1200x480px simply because it seems visually pleasing to me — at least on my large monitor!

At this point you are free to:

  1. Select your desired images (the carousel can handle as many as you’d like).
  2. Edit them to your desired dimensions (keeping them consistent).
  3. Wrap the images in links if you’d like (as I have done in the demo).
  4. Supply your desired captions.

The Results

Always remember, as you try things out and tweak them, Twitter Bootstrap’s excellent documentation is your friend. And if you can use additional help, a lot of folks find help in the Twitter Bootstrap Google Group.

Take a look at the final result.

Series Navigation<< Twitter Bootstrap 101: Tabs and PillsTwitter Bootstrap 101: Trimming File Size >>

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.soapboyfresh.com Ricardo

    Thanks again David (you make it so easy to pickup bootstrap) love all the tutorials, can’t wait until the next one. Maybe one about adding e commerce product page (ex: bigcartel), gallery page, contact page, or creating a mobile app page using twitter bootstrap.

    Thanks again
    Ricardo

  • http://oneprism.com Joe

    Spelling mistake in Step 4. “Plahold.it” should be “Placehold.it”.

    • http://www.snaptin.com Ian Yates

      Yep, corrected – thanks for the pick up.

  • http://grantpalin.com Grant Palin

    If this is implemented with an HTML5 doctype, the individual images could be better represented with figure and figcaption elements. This would add some semantic meaning in place of generic div elements.

    div.item –> figure
    div.carousel-caption –> figcaption

    The item and carousel-caption classes might not be needed either, as the script/CSS should be able to work off the semantic elements.

    Just a thought!

  • supporf

    final the serie continues
    thanks you very mutch

  • http://www.tinocordes.dk/webdesign Tino Cordes

    I’ve started to use Bootstrap a few months ago. It’s really great! And i’m normally not a big fan of using predefined code like this on my clients websites. But I save time and the websites are better :-)

  • Simon

    It doesn’t seem to work correctly in Opera (12.0 at least), it doesn’t scroll through the gallery.

    • Colin

      Same problem for me on Opera 12 as well.

  • http://www.concrete5.org/r/-/365 synlag

    Great series!
    Thanks for this,

    bw
    Ron

  • Hamid

    really thx David Cochran for the series, i was waiting many week for this series.

    and i wanted to say that to anyone whos posting an article or video tut from your team: it’s really good if you guys supporting both mac and windows, because i downloaded many articles and videos from webdesign or net.tutsplus and i noticed that you need to supporting for both mac and win like other companies such lynda video2brain and etc, i wanted to say that long time ago but anywa, i’m still say thank you guys and ofc i’m still using tutsplus team’s websites, Cheer.

    Best Regard
    Hamid.

  • http://www.open-is.co.za Wayne

    Thanks for taking the time to do this.

    It has been most informative.

  • Mike

    Hi David (or anyone willing to help :) ) I just installed this carousel on a test page and it works fine however if I change the image size to something like 320×280 the images are left justified. If I center them then the caption is off as well. Any ideas? Can you also constrain the controls to that width? Thanks!

  • elisabetta

    Hi David and thanks for these great tutorials!
    I’m now working on carousel, and was able to use my images; they are 850×250 and so the caption is too long and the images aren’t centered in the page: how can I solve this problem?
    Second question: how can I merge bootstrap and Joomla template? I’m now using Joomla 3alfa and saw there is protostar template built with bootstrap, but can’t imagine how to customize it regarding background and links colors, navbar and so on…
    A tutorial about this could be great!!

  • Henk

    Hi, thanks-a-bunch for the great tuts+ !!
    One quick question however: why does not the carousel image correspond with the grid-width of 940 px??
    Seems more logical to me.
    Keep it up!

    • Sdwrage

      960px would be the most mathematically elegant width.

  • rkb

    Images was still cut off when using diff size screens, with a manual width of 100% fixed this but really to say its mean to do all this already on about 50 tests none of them enabled it to resized it to all screens used, it should centre the image or stretch it sadly it does not do eva of these things, thanks for the tut tho very useful.

    • Joe Hart

      If you want the image stretched you’d have to add height=100% also. If you do just width then it keeps the image proportional and cuts into the bottom.

  • Joel

    Is there any way to make it so the carousel doesn’t automatically run through the slides?

    • Joe Hart

      I haven’t tried this yet but I’d go look at the bootstrap-carousel.js and look on line 40 and change paused=false to paused=true. If that doesn’t work look around on google. I’ve seen this question before.

  • M. T. Rahman

    Thank you very much. Could we use it for our commercial project? The ‘terms & conditions’ section is telling that we can use the knowledge but not the code. The implementation of knowledge and the tutorial requires to use the code. With the open source free resources, hope we can practically utilize the valuable lessons from tutsplus, not just reading and searching for other resources. Will appreciate your kind response.

  • Oliver

    Thanks for the tuts. I used the tabs one, which was great. Can you do one on getting a properly working accordion with bootstrap? Mine works OK for the first open & close, but then stops responding.

  • Fariss

    is there any whey to change the animation speed

    • Joe Hart

      animation speed is in the bootstrap-carousel.js on line 175. If you follow the demo you can over ride the speed by adding the script the author has in the head an changing the default 5000 miliseconds to something like 10000

  • Pingback: slidechaud » Tuto : créer un slideshow avec meteor.js et twitter bootstrap

  • koko

    Hello, is there a way to get the carousel index when hooking the slide method?
    example

    $(‘#myCarousel’).bind(‘slid’, function() {
    alert(‘This is picture number …’);
    });

  • Pingback: Twitter Bootstrap | When the code is singing ^__^