HTML & CSS - - By George Martsoukos

A Full Screen Bootstrap Carousel with Random Initial Image

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.

Sponsors
Login or Create Account to Comment
Login Create Account