Reputation: 1911
I've been trying to hide the Bootstrap Carousel left and right buttons if only one slider is present but can't seem to get it to work properly.
I've tried
if ($('.carousel-inner div').length === 1 ) {
$(this).find('.controls .carousel-control').hide();
}
and
if($('.carousel-inner .item').is(':only-child')) {
$(this).find('.controls .carousel-control').hide();
Without any luck.
Is there a particular reason why neither of these would work? The console returns the correct number of sliders for .length
and I use the exact same .hide
method on a different function dealing with this carousel.
Upvotes: 7
Views: 12371
Reputation: 19
Try this for Bootstrap 4+
$('.carousel-inner').each(function() {
if ($(this).children('div').length === 1) $(this).siblings('.carousel-indicators, .carousel-control-prev, .carousel-control-next').hide();
});
Upvotes: 1
Reputation: 6574
The accepted answer works fine so long as you have 1 carousel per page. I had a couple so thought I'd add to the solution:
Based on using the standard Bootstrap Carousel Mark up:
<div id="myCarousel" class="carousel slide">
<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>
<!-- Carousel items -->
<div class="carousel-inner">
<div class="active item">…</div>
<div class="item">…</div>
<div class="item">…</div>
</div>
<!-- Carousel nav -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">‹</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">›</a>
</div>
You'll want to iterate through each occurrence of a carousel, use $(this) and grab its siblings:
$('.carousel-inner').each(function() {
if ($(this).children('div').length === 1) $(this).siblings('.carousel-control, .carousel-indicators').hide();
});
Upvotes: 14
Reputation: 10743
Instead of $(this).find(...).hide();
try $('.controls .carousel-control').hide();
Upvotes: 7