Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable a button at the last slide of a carousel?

I am using bootstrap carousel and I want to stop the carousel from sliding when it reaches the last slide ( stop at the last slide), and then disable the "next" button

like image 958
anyavacy Avatar asked Sep 02 '25 10:09

anyavacy


1 Answers

To disable the carousel from "wrapping" there's an option. You can either set data-wrap="false" on the carousel or just put it in the options when you initialize the carousel.

To handle the disabling of the next/previous buttons, I think the answer from Naliza works fine, but it's an awful lot of code. Here's a shorter version that handles setting the wrap property to false as well:

jQuery to initialize carousel and show/hide previous/next arrows:

$('.carousel').carousel({
  wrap: false
}).on('slid.bs.carousel', function () {
    curSlide = $('.active');
  if(curSlide.is( ':first-child' )) {
     $('.left').hide();
     return;
  } else {
     $('.left').show();   
  }
  if (curSlide.is( ':last-child' )) {
     $('.right').hide();
     return;
  } else {
     $('.right').show();      
  }
});

Since the event handler only runs after the carousel slides, you want to set the .left to display: none in your css so when the carousel is displayed when the page is loaded the left arrow is hidden. Then as soon as the carousel slides for the first time, the code above will display the left arrow.

CSS:

.left {
  display: none;
}

I won't include the HTML as this is designed to work with boilerplate Bootstrap carousel markup.

DEMO

like image 117
jme11 Avatar answered Sep 04 '25 02:09

jme11