Search code examples
jquerytwitter-bootstrapcarouseltwitter-bootstrap-2

Bootstrap carousel: prevent next/prev or indicator buttons while animating


I am trying to make a small function to stop the next/prev buttons and indicators from sliding around while the carousel is animating.

JSFiddle Example

I've tried:

$('.carousel').on('slid',function() {
   var carousel = $(this);
   function preventClick() {
       carousel.on('click','.carousel-indicators li, .carousel-control', function() {
            return false;
       });    
   }


   function releaseClick() {
       setTimeout(function() {
           carousel.on('click','.carousel-indicators li, .carousel-control', function() {
               return true;
           });
       }, 2000);    
   }
   preventClick(); releaseClick();
});

Any idea why this doesn't work? Or perhaps you have a better idea?


Solution

  • If I understand what you want correctly, you can achieve this with the use of the disabled attribute.

    JSFiddle Demo

    Take a look at the following code:

    var myCarousel = $("#myCarousel");
    
    //bind forcePause() to the slide event for our carousel
    myCarousel.on('slide',{ pauseAmount: 5000}, forcePause);
    
    /**  setTimeout and disable all carousel navigation   *
    *    properties for the duration of the pause         */
    function forcePause(event){
        //extract pauseAmount from our bound data
        var pauseAmount = event.data.pauseAmount
    
        //get all the navigation properties of myCarousel
        var carouselNavElements = myCarousel.find(
            "a[href=#myCarousel], li[data-target=#myCarousel]"
        );
    
        //set the disabled attribute to true for the carousel's nav elements
        carouselNavElements.prop('disabled', true);
        console.log('pause started');
    
        //set the timer with the pauseAmount
        setTimeout(function(){
            console.log('pause finished');
    
            //"reenable" the nav elements
            carouselNavElements.prop('disabled', false);
        }, pauseAmount);
    }
    
    //this is already built-in functionality for anchors in bootstrap, just add support for li
    $('body').on('click', 'li.disabled', function(event) {
        event.preventDefault();
    });
    

    Keep in mind that we bound it to the slide event so this will force a pause of the automatic event triggering of the carousel as well ie:

    myCarousel.carousel({
      interval: 2000 
    });
    

    If that's unwanted, you can change the event to click and bind it to the nav elements but you'll have to manually manage the event.