A Full-screen Bootstrap Carousel with Random Initial Image

Share this article

A Full-screen Bootstrap Carousel

In this article, 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:

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

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:

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="#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:

See the Pen Full-screen Bootstrap 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 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 finds carousels useful anymore, you might have a client ask for such a feature and maybe these customizations will come in handy.

If you’ve got the basics of Bootstrap under your belt but are wondering how to take your Bootstrap skills to the next level, check out our Building Your First Website with Bootstrap 4 course for a quick and fun introduction to the power of Bootstrap.

How can I make my Bootstrap Carousel full-screen?

To make your Bootstrap Carousel full-screen, you need to modify the CSS properties of the carousel. Set the height and width properties of the carousel to 100%. Also, ensure that the images you use for the carousel are of high resolution to prevent pixelation when viewed in full-screen mode.

How can I add a random initial image to my Bootstrap Carousel?

To add a random initial image to your Bootstrap Carousel, you need to use JavaScript. You can create an array of images and then use the Math.random() function to select a random image from the array each time the page loads.

How can I add captions to the images in my Bootstrap Carousel?

To add captions to the images in your Bootstrap Carousel, you can use the “carousel-caption” class provided by Bootstrap. This class allows you to add a title and a description to each image in the carousel.

How can I add navigation controls to my Bootstrap Carousel?

To add navigation controls to your Bootstrap Carousel, you can use the “carousel-control-prev” and “carousel-control-next” classes provided by Bootstrap. These classes allow you to add previous and next buttons to the carousel.

How can I add indicators to my Bootstrap Carousel?

To add indicators to your Bootstrap Carousel, you can use the “carousel-indicators” class provided by Bootstrap. This class allows you to add small circles at the bottom of the carousel that indicate the current slide.

How can I make my Bootstrap Carousel auto-slide?

To make your Bootstrap Carousel auto-slide, you can use the “data-ride” attribute provided by Bootstrap. Set the value of this attribute to “carousel” to make the carousel auto-slide.

How can I pause the auto-sliding of my Bootstrap Carousel on hover?

To pause the auto-sliding of your Bootstrap Carousel on hover, you can use the “data-pause” attribute provided by Bootstrap. Set the value of this attribute to “hover” to pause the auto-sliding on hover.

How can I change the transition effect of my Bootstrap Carousel?

To change the transition effect of your Bootstrap Carousel, you can use the “data-interval” attribute provided by Bootstrap. This attribute allows you to set the time interval between slides, thus controlling the speed of the transition effect.

How can I make my Bootstrap Carousel responsive?

To make your Bootstrap Carousel responsive, you need to use the responsive classes provided by Bootstrap. These classes allow you to specify different layouts for different screen sizes.

How can I add a fade effect to my Bootstrap Carousel?

To add a fade effect to your Bootstrap Carousel, you can use the “carousel-fade” class provided by Bootstrap. This class changes the transition effect from sliding to fading.

George MartsoukosGeorge Martsoukos
View Author

George is a freelance web developer and an enthusiast writer for some of the largest web development magazines in the world (SitePoint, Tuts+). He loves anything related to the Web and he is addicted to learning new technologies every day.

bootstrapbootstrap carouselbootstrap-hubBootstrap-tutorialsjQueryLouisL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week