Create a Responsive Image Carousel using Twitter Bootstrap and jQuery

Posted by: Suprotim Agarwal , on 8/29/2015, in Category jQuery and ASP.NET
Views: 38530
Abstract: Using Twitter Bootstrap and jQuery to create an Image Carousel with Responsive Design

Users expect to be able to view your website on any device they’ve got in their hands. For websites now-a-days, delivering an optimal user experience to all devices—including tablets, smartphones, laptops, and large screens; is a major task to achieve. Responsive web design is the answer to it, which provides the platform and flexibility where we can write code once and publish the application everywhere.

 

Twitter's Bootstrap library (http://getbootstrap.com/) is the most popular responsive framework as of this writing.

Today we will create an Image Slider using Responsive Web Design with the Twitter's Bootstrap Library. When it comes to creating either a slide show or an image carousel for your websites, the Twitter Bootstrap carousel plugin is a good choice. All you need is some structured markup, the Bootstrap plugin, and a couple of lines of jQuery Code.

Create a new HTML file and call it ‘BootstrapImageCarousel.html’. Start by defining a parent container <div> tag with the following class:

<div id="imgcarousel" class="carousel" data-ride="carousel"></div>

To create indicators, we will create an ordered list with a standard bootstrap class ‘carousel-indicator’ and add some list items in it. The data-target is set to imgcarousel and data-slide-to indicating the position to slide to.

<div id="imgcarousel" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
        <li data-target="#imgcarousel" data-slide-to="0" class="active"></li>
        <li data-target="#imgcarousel" data-slide-to="1"></li>
        <li data-target="#imgcarousel" data-slide-to="2"></li>
        <li data-target="#imgcarousel" data-slide-to="3"></li>
    </ol>
</div>

If you observe, the first <li> item has a class set to active which specifies that it is the first slide that you are going to see. In addition to the carousel class, we have also decorated the div with the slide class which gives it a nice sliding effect when going from one image to another.

HTML5 is designed with extensibility. The custom data-* attributes allow us to store some useful private information on standard HTML elements which the end user can’t see nor does it affect the layout in any way. Bootstrap uses the "data-target" attribute to specify which element the behavior applies to. In our case, we have set the data-target to #imgcarousel.

It’s time to start defining the structure for the slides. For each slide, we will create a <div> with class item. Inside each item, we will create an image that we want to add to the carousel, with the src set to the image location, an alt attribute and a class set to img-responsive. The img-responsive class makes sure that your image scales to suit screens of all sizes.

<div class="carousel-inner">
    <div class="item active">
        <img src="http://placehold.it/1200x600" 
                alt="My First Image" class="img-responsive"/>
    </div>

    <div class="item">
        <img src="http://placehold.it/1200x600"
            alt="My Second Image" class="img-responsive" />
    </div>
    ...

</div>

The first item has a class active to indicate this is the first image to load which corresponds to the <li> item that was set to active, as you can see in the code.

If you save and browse the page now, you will be able to see a slide show.

Let’s add some features to it. We will add two arrows, one on the left and the other to the right which will help us navigate through the images. Just after the <div class=”carousel-inner”> add navigational controls as follows:

<!-- Navigation Controls -->
<a class="left carousel-control" href="#imgcarousel" data-slide="prev">
    <span class="icon-prev"></span>
</a>

    <a class="right carousel-control" href="#imgcarousel" data-slide="next">
    <span class="icon-next"></span>
</a>

One final bit is to add a caption and description to every image. Go back to <div class=”carousel-inner”> and a <div class=”carousel-caption”> to each of the div, as shown here.

<div class="item active">
    <img src="http://placehold.it/1200x600" 
            alt="My First Image" class="img-responsive"/>
    <div class="carousel-caption">
        <h1>First Image</h1>
        <p>This is my first Image</p>
    </div>
</div>

That’s it. Save and browse the page and you will see you have an Image Carousal that works across different devices. Resize the browser size and the carousel adjusts itself to accommodate in the new space.

Image Carousal

Live Demo: http://www.jquerycookbook.com/demos/S6-Images/51-BootstrapImageCarousel.html

The carousel component is not compliant with accessibility standards.

Where to use jQuery?

Some of you may be wondering that we have created an entire Image Carousal example without using a single line of jQuery code. Well there are certain options which may be passed to the carousel() Bootstrap method to customize it’s functionality. Here’s where jQuery fits in. We will see some examples of using jQuery to programmatically customize the carousal widget functionality.

Change the Interval of the Slider:

The default interval between one slide to another is 5000 milliseconds. We can change the interval or even stop the carousal by setting interval to false. In this example, we have changed the interval to 2000 milliseconds (2 seconds).

$('.carousel').carousel({
    interval: 2000
})

Similarly setting the wrap option to false tells the carousal to stop at the last slide and not cycle through the slides automatically.

Start the Slider from a different Slide Number

Say you want to start the slide show from the 4th frame, just specify the following:

$('.carousel').carousel(3);

Note: The frame number is 0 based.

Use your own Buttons to go to the Previous or Next slide

If you want to add your own buttons and use it to move to the next or previous slide, you can use jQuery in the following way:

$(function(){
    $('#btnprev').on('click',function(){
        $('.carousel').carousel('prev');
    });

    $('#btnnext').on('click',function(){
        $('.carousel').carousel('next');
    });
}

Here we are assuming we have a Next and Previous Button on our page with id as btnnext and btnprev respectively.

Handle Events in the carousal

You can hook events in the carousal. Let’s say you want to display a message when the carousal has completed its slide transition. You can use the slid.bs.carousel event in the following manner:

$(function () {
    $('.carousel').on('slid.bs.carousel', function () {
        console.log('previous slide transition completed');
    });
});

This will print the message in the console every time a slide transition occurs.

Did you like this article? This article was taken from my new jQuery book The Absolutely Awesome jQuery Cookbook which contains scores of similar practical jQuery/jQueryUI recipes you can use in your projects right away.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook