Zach Shallbetter
Zach Shallbetter

Reputation: 1911

Hide Twitter Bootstrap left and right arrows if only one slider is present

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

Answers (3)

Franz Josef Caballes
Franz Josef Caballes

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

GuyC
GuyC

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">&lsaquo;</a>
  <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</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

BumbleB2na
BumbleB2na

Reputation: 10743

Instead of $(this).find(...).hide(); try $('.controls .carousel-control').hide();

Upvotes: 7

Related Questions