Chapter 2: A Full-screen Bootstrap Carousel with Random Initial Image

by George Martsoukos

In this chapter, I'm going to build two simple extensions for the Bootstrap carousel. First, I’ll create a full-screen Bootstrap Carousel 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="carouselExampleIndicators" class="carousel slide" data-ride="carousel">

  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active">
    </li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="1.jpg" data-color="lightblue" 
      alt="First Image">
      <div class="carousel-caption d-none d-md-block">
        <h5>First Image</h5>
      </div>
    </div>
    <div class="carousel-item">
      <!-- slide content -->
    </div>
    <div class="carousel-item">
      <!-- slide content -->
    </div>

    <!-- more slides -->
  </div>

  <!-- Controls -->
  <a class="carousel-control-prev" href="#carouselExampleIndicators" 
  role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" 
  role="button" data-slide="next">
    <span class="carousel-control-next-icon" 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:

Bootstrap Carousel structure

Live Code

Creating Full-screen Bootstrap Carousel Slides

At this point we’ll go one step further, converting the existing carousel into a full-screen Bootstrap Carousel 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);
});

Next, we add 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">
  <div class="carousel-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:

Live Code

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="#carouselExampleIndicators" data-slide-to="0" class="active"></li>

<!-- etc... -->

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

<!-- etc... -->

Which now becomes:


<!-- etc... -->

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

<!-- etc... -->

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

<!-- etc... -->

If you’re using jQuery to add the active class to the first slide, as I explained earlier, you’d 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 = $('.carousel-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');
  }
});
  • 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:

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 custom event).

Conclusion

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.2.122