How to loop bootstrap Carousels?
13,678
Yes, first slide has to have active
class to automatically show it on init.
Try this:
{{--*/ $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 $isFirst
variable, what stays true
until first slide has been printed. This way we can add active
class for first slide and not for others.
Author by
scott
Updated on July 16, 2022Comments
-
scott almost 2 years
i am trying to loop carousels 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 works only if i add 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 above code then slider not display any images.i think i need to keep my fist slider image need to be active .how to achieve that without adding default active code ?thank you in advance
-
Rene Korss almost 9 yearsI added little explanation to my answer.
-
scott almost 9 yearssorry .it works ok.and one question, is my code is correct in the sense i used for loop in carousel-indicators.
-
Rene Korss almost 9 yearsYes.
for
looks great for this.