Reputation: 15490
I am implementing a Bootstrap 4 Carousel on my site and have come up against a problem:
The Carousel seems to need the .active
class to be set on the first slide otherwise it wont work. With the way I've implemented the Carousel in my CMS, I've used a single template file for the slide (with dynamic content within), allowing me to implement an unlimited number of slides. However, I cannot set the initial slide to have the .active
class without that class appearing on all of them, and breaking the carousel.
I could use some JQuery to add that class to the first instance of a slide, but I'm hoping there's a way around this (to me it seems a bit of an oversight of Bootstrap).
Would anyone know if this is possible?
Upvotes: 1
Views: 2013
Reputation: 1509
You can use jquery to add class active. this will solve the issue
$(document).ready(function () {
$('#myCarousel').find('.item').first().addClass('active');
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Carousel Example</h2>
<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>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item">
<img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos6.jpg" alt="Los Angeles" style="width:100%;">
</div>
<div class="item">
<img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos4.jpg" alt="Chicago" style="width:100%;">
</div>
<div class="item">
<img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos7.jpg" alt="New york" style="width:100%;">
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</body>
</html>
Upvotes: 2