How to make Bootstrap 3’s Carousel truly responsive

If youre like me, you love the fact that Bootstrap is a mobile first responsive HTML5 Framework, but there was something missing in v3: a Responsive carousel!

For a project, I needed a carousel that works with screens from an iPhone up to a 4k 85, so I had to find a way. See DEMO

Here it is, a simple JavaScript addon that make Bootstrap 3 Carousel responsive.

The principle is mobile first, like always, with a fallback if not supported.

  1. You will need all images of all sizes

My system CANNOT create the different sizes needed to work, so, for each slide, you will need the same image, for each size you need. try naming them with a convention like

  • slide1-sm.png or slide1-0768.jpg
  • slide1-md.png or slide1-1024.jpg
  • slide1-lg.png or slide1-1280.jpg
  • slide1-xl.png or slide1-1600.jpg

html

What you need to change in your HTML is 2 things

First, settup your sizes

Add you break-point sizes in the div that define your carousel with
data-sizes='{"sm":768, "md":1024, "lg":1280, "xl":1600}'
Like this

<div id="carousel-example-generic" data-sizes='{"sm":768, "md":1024, "lg":1280, "xl":1600}' data-ride="carousel" class="carousel slide">

then, for EACH item images, you need to add the different images sizes as data like this :

<img class="" src="images/carousel-0768.png" data-sm="images/carousel-0768.png" data-md="images/carousel-1024.png" data-lg="images/carousel-1280.png" data-xl="images/carousel-1600.png" alt="Image 1">

JAVASCRIPT

Somewhere on your page, you need to add this function:

function responsiveCarrousel(rc_carrousel, rc_imgs) {
    var rc_lgtotake = 'src';
    var rc_screensize = $(window).width();
    var rc_sizes = rc_carrousel.data('sizes');
    $.each(rc_sizes, function (key, value) {
        if (value <= rc_screensize) {
            rc_lgtotake = key;
        }
    });
    rc_imgs.each(function () {
        if (rc_lgtotake != 'src') {
            $(this).attr('src', $(this).data(rc_lgtotake));
        }
    });
}

Then you need to activate it when needed.

$(function () {
    // this line make resize on page load
    responsiveCarrousel($('#carousel-example-generic'), $('.carousel-inner .item img'));

    // This section is not neccessary, and MAY slow down old phones/computer when totating/changing size
    $(window).resize(function () {
        responsiveCarrousel($('#carousel-example-generic'), $('.carousel-inner .item img'));
    });
});

Now this should work, Hopefully, their will be a better way in Bootstrap V4!