Search code examples
javascriptjquerytwitter-bootstrap

How to stop bootstrap carousel on first cycle


I want a slider to start sliding and it should stop at first cycle on first image of the slide/carousel.

var imgCount = 3;
$('#myCarousel').carousel({
    interval: 2500
});
$('#myCarousel').bind('slid',function(){
    imgCount--;
    if(imgCount == 3)
        $('#myCarousel').carousel('pause');  
});

I also tried following code.

$('#myCarousel').carousel({
    interval: 2500
});
$('#myCarousel').bind('slid',function(){
    var count = 3;

    count--;
    if(count == 0)
    {

        slide.stopAutoPlay();
    }

});

For some reason its not working. I am using stript tag right after bootstrap script file source.


Solution

  • The wrap option serves to stop the carousel on the first cycle. But it remains on the last page after it has completed.

    <div id="carousel-example" class="carousel slide" data-ride="carousel" data-wrap="false">
    

    or

    $('.carousel').carousel({ wrap: false });
    

    If you want it to stop at a specific slide count this code will help you to achieve that

    var count = 1;
    
    $('.carousel').carousel();
    $('.carousel').on('slid.bs.carousel', function () {
        count--;
        if (count <= 0) {
            $('.carousel').carousel('pause');
        }
    });
    

    {Edit}

    Also if you want to reset the carousel's position and move to the first page after stopping you add this after pausing

    var count = 1;
    
    $('.carousel').carousel();
    $('.carousel').on('slid.bs.carousel', function () {
        count--;
        if (count <= 0) {
            $('.carousel').carousel('pause');
            // Reset the carousel position
            setTimeout(function () {
                $('.carousel').carousel(0);
            }, 200);
        }
    });
    

    You need to set a timeout to allow the transition to finish or the carousel might have glitches after it has completed.