How to loop the bootstrap carousel?
I am trying to execute carousel from mysql data.the following is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="bs-example">
<div id="myCarousel" class="carousel slide" data-interval="2000" data-ride="carousel">
<!-- Carousel indicators -->
<ol class="carousel-indicators">
@for($i=0;$i<=count($data);$i++)
<li data-target="#myCarousel" data-slide-to="{{$i}}" class=""></li>
@endfor;
</ol>
<!-- Wrapper for carousel items -->
<div class="carousel-inner">
<div class="active item">
<img src="images/1.jpg" alt="First Slide">
<div class="carousel-caption">
<h3>First slide label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
@foreach($data as $val)
<div class="item">
<img src="{{ $val['featured_image']}}" alt="Second Slide">
<div class="carousel-caption">
<h3>{{ $val['title']}}</h3>
<p>{{ $val['description']}}</p>
</div>
</div>
@endforeach
</div>
<a class="carousel-control left" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
</body>
</html>
the above code only works if i add the following line
<div class="active item">
<img src="images/1.jpg" alt="First Slide">
<div class="carousel-caption">
<h3>First slide label</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
if i remove the code above then the slider doesn't display any images. I think I need my fist slider to be active. How can I achieve this without adding the default active code? thanks in advance
source to share
Yes, the first slide must have a class active
to show it automatically in init.
Try the following:
{{--*/ $isFirst = true; /*--}}
@foreach($data as $val)
<div class="item{{{ $isFirst ? ' active' : '' }}}">
<img src="{{ $val['featured_image']}}" alt="Second Slide">
<div class="carousel-caption">
<h3>{{ $val['title']}}</h3>
<p>{{ $val['description']}}</p>
</div>
</div>
{{--*/ $isFirst = false; /*--}}
@endforeach
So, I created a variable $isFirst
that stays on true
until the first slide is printed. This way we can add a class active
for the first slide and not the others.
source to share