Wednesday, February 14, 2018

A Full-screen Bootstrap Carousel with Random Initial Image

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:

[code language="html"]
<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>
[/code]

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:

[code language="javascript"]
$('.carousel').carousel({
interval: 6000,
pause: "false"
});
[/code]

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.

Continue reading %A Full-screen Bootstrap Carousel with Random Initial Image%


by George Martsoukos via SitePoint

No comments:

Post a Comment