HTML & CSS
Article

A Full Screen Bootstrap Carousel with Random Initial Image

By George Martsoukos

A few months ago, I wrote an article that covered Bootstrap’s Affix and ScrollSpy components. This time though, I’ll be focused on a different Bootstrap component: I’ll go through the process of building two simple extensions for the Bootstrap carousel.

First, I’ll create a full-screen slideshow and then I’ll show you how to randomize the first slide on page load.

But before digging into those extensions, let’s start by creating a carousel based on the default styles.

To create the carousel, we’ll take advantage of the basic code for the carousel component that Bootstrap provides:

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

  <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src="1.jpg" data-color="lightblue" alt="First Image">
      <div class="carousel-caption">
        <h3>First Image</h3>
      </div>
    </div>
    <div class="item">
      <img src="2.jpg" data-color="firebrick" alt="Second Image">
      <div class="carousel-caption">
        <h3>Second Image</h3>
      </div>
    </div>
    <!-- more slides here -->
  </div>

  <!-- Controls -->
  <a class="left carousel-control" href="#mycarousel" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#mycarousel" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

Notice that each of our images contains the custom data-color attribute. Later we’ll use its value as a fallback in case the corresponding image fails to load.

The next step is to initialize the carousel via JavaScript and modify the predefined values of the interval and pause configuration properties. Take note that we choose to set the value of the pause property to false because we always want the cycling to be active:

$('.carousel').carousel({
  interval: 6000,
  pause: "false"
});

Having followed those simple steps (and of course imported the required files), we should now be able to build the first version of the carousel. Here’s how it looks so far:

See the Pen A Basic Bootstrap Carousel by SitePoint (@SitePoint) on CodePen.

Creating Full-screen Slides

At this point we’ll go one step further, converting the existing carousel into a full-screen slideshow. To implement this updated version we have to add some custom jQuery:

var $item = $('.carousel .item');
var $wHeight = $(window).height();

$item.height($wHeight); 
$item.addClass('full-screen');

$('.carousel img').each(function() {
  var $src = $(this).attr('src');
  var $color = $(this).attr('data-color');
  $(this).parent().css({
    'background-image' : 'url(' + $src + ')',
    'background-color' : $color
  });
  $(this).remove();
});

$(window).on('resize', function (){
  $wHeight = $(window).height();
  $item.height($wHeight);
});

…and some CSS:

.full-screen {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

In the code above, we do the following:

  • Loop through our images and get the values of the src and data-color attributes.
  • Find their direct parent (.item) and assign the full-screen class along with a few background-related properties to it. Keep in mind that the values of those properties depend on the values of the aforementioned attributes (which are different for each image).
  • Set the height of the parent element equal to the viewport height. It’s important to mention that we have to recalculate the height of the browser window, when it changes size (using the resize event).
  • Remove the img elements which are not needed since we are relying on the backgrounds.

Although it’s not required, let’s make one last change. When the page loads, we’ll add the active class to the first slide using jQuery, rather than having it hard-coded in the HTML:

So instead of this:

<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
  <div class="item active">

We do this:

$item.eq(0).addClass('active');

This allows us to prevent a small toggle that is possible to occur between the two different heights (before and after the changes we made) of the first slide.

Here’s the new version of our slideshow:

See the Pen Bootstrap Carousel Full Screen by SitePoint (@SitePoint) on CodePen.

It might help to view the full page version to see the difference from the previous example.

Initializing a Random Slide

Sometimes we might want to show a random slide, when the page loads. To build this new functionality, we should update our code. To begin with, we have to remove the default active class from the first slide as well as the first indicator.

Here’s the original code:

<!-- etc... -->

<li data-target="#mycarousel" data-slide-to="0" class="active"></li>

<!-- etc... -->

<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
  <div class="item active">

<!-- etc... -->

Which now becomes:

<!-- etc... -->

<li data-target="#mycarousel" data-slide-to="0"></li>

<!-- etc... -->

<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
  <div class="item">

<!-- etc... -->

If you’re using jQuery to add the active class to the first slide, as I explained earlier, then you would need to remove that code after adding the new random slide code.

We can now add the following code snippet to the existing jQuery:

var $numberofSlides = $('.item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));

$('.carousel-indicators li').each(function(){
  var $slideValue = $(this).attr('data-slide-to');
  if($currentSlide == $slideValue) {
    $(this).addClass('active');
    $item.eq($slideValue).addClass('active');
  } else {
    $(this).removeClass('active');
    $item.eq($slideValue).removeClass('active');
  }
});

So again, let me clarify what’s happening here:

  • We start by getting the total number of slides and use this value to find a random slide.
  • We iterate through the carousel indicators and retrieve the value of the data-slide-to attribute. If the random number matches the value of this attribute, we assign the active class to the corresponding slide and indicator. If that doesn’t happen, we remove it from the target elements.

Of course, if you don’t want to combine this behavior with the full-page slideshow, feel free to remove the unnecessary code.

You can see this functionality in the following CodePen demo:

See the Pen Bootstrap Full-screen Carousel with Random Initial Image by SitePoint (@SitePoint) on CodePen.

If you click the “RERUN” button on the CodePen embed, you’ll see the initial image change on each load.

Potential Further Customizations?

Beyond the extensions presented in this article, there are many other ways to change the predefined behavior of the carousel component. If you feel adventurous, here are a few other ideas you can examine:

  • Create additional animation effects (e.g. fade or scale) when switching between slides
  • Build an image overlay
  • Randomize the next and previous slides (use the slide.bs.carousel method)

Conclusion

In this article, I showed you how to add more flexibility to your Bootstrap projects by customizing the carousel component. Although not everyone finds carousels useful anymore, you might have a client ask for such a feature and maybe these customizations will come in handy.

  • http://michaelwoodruff.com/ Michael Woodruff

    How would you recommend adding touch support?

  • http://michaelwoodruff.com/ Michael Woodruff

    Thanks!

  • Byron Jones

    I am trying to follow along working on an existing site, but once I remove the “active” from the class in HTML, the carousel disappears from the page. It appears the “random” part of the code is not actually assigning a slide as active, so nothing shows. Is there a specific place the “random” code should go. You mention to put it into the existing jQuery. The page I have has four .js files attached to it. Does it matter which file I include it on? If so, how can I figure it out? I placed it into the same file that aids a page preloader and customizes a scrollbar because it was one I made and not a minified version from someone else.

    • http://careersreport.com Dawnd Papp

      Here is a way how it is possible to get paid $fifty five /an hour… After being without work for 6 months , I started making money over this internet site and now I possibly can not be happier. After 3 months doing this my income is around 5000 bucks-per month -Check link on ___MY-___PROFILE____ for more info

    • http://georgemarts.com/ George Martsoukos

      Can you please provide a working demo? No, you can place the “random” code anywhere in your JS file. Just make sure that jQuery has been loaded in your page.

      • Marz

        Same issue here. The active class is added by jQuery in my code and the slides are auto generated by a CMS. Once I remove the addClass and replace it with your random js code the page goes blank. I know jQuery is loaded because the non random solution works and it’s a live site. Any insights?

    • Vasilija Švigirova Vučja

      You probably forgot to add this:

      var $item = $(‘.carousel .item’);

  • Jay Cole

    I’m trying to add content on top of the carousel, but the content on the carousel is also affected by the fade switch, how can I fix this?

    • http://georgemarts.com/ George Martsoukos

      What do you want to create? Do you want to have a fixed content on top of the carousel?

  • Innocent Monareng

    I have a multiple sliders in my website would like these setting to apply to only one slider with id of carousel1. How can I go about that?

    I tried adding the following but didn’t work:
    $(‘#carousel1’).find(‘.carousel’);
    and
    $(‘#carousel1’).find(‘.carousel img’)…

  • Lee Also

    I would like to have a png stationary over the slides… Over to one side, while the slides change underneath it.

    What do I need to do?

  • Heiko Torner

    Very nice work, thanks a lot.
    What I like to do next is to place some text right on top of the slider-images, with the normal row/col scheme from bootstrap. Any idea how to achieve this?

    • http://georgemarts.com/ George Martsoukos

      One possible way is to create a fixed positioned element. By default, this will be positioned relative to the viewport (apart from a very specific case). If you want different text for each slide, you can either use some JS to modify its content depending on the active item or even better add some nested elements to this element and use CSS to show them sequentially depending on the active item.

  • CraigR

    Nice tutorial

    I has one issue, my console threw an error with the code snippet for the random image
    i fixed it by changing the lines

    $item.eq($slideValue).addClass(‘active’);
    and
    $item.eq($slideValue).removeClass(‘active’);

    to

    $(‘.item’).eq($slideValue).addClass(‘active’);
    and
    $(‘.item’).eq($slideValue).removeClass(‘active’);

  • Jyoti Rana

    how can i create a form on caurosel plz help

  • Joel Santos

    Hey. firts of all nice work on the code. Im having a little problem. I copied the copy as it is. I created individual sheets for the html, css and java and i think im doing the good connection on the code but im having a “Uncaught ReferenceError: $ is not defined” and i think the java isnt working because the images appear all at the same time. Im not a pro coder so i could use some help.

  • Viva

    Hi George, How can randomize not only the start of slide show, but each picture that will follow the next?

  • Jon Wilcox

    How would one go about making the first image in the carousel random while leaving the remaining image order intact?

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.