Search code examples
javascriptbootstrap-4tabscycle

Is there a way to cycle through Bootstrap tabs automatically (similar to carousel)?


I would like the Bootstrap tabs to cycle through each tab, kind of like a carousel, changing every 10 seconds or so. I figure it's going to require some custom javascript (but I'm a bit of a novice)!

(I'd also like the cycle to stop if a tab has been manually clicked, but that's more of a 'stretch goal'!)

Here's what I've got so far: http://jsfiddle.net/59Lyhqmn/31/

I've tried implementing solutions from similar questions, such as:

$(function(){
var tabs = $('#myTab a');
    var counter = 0;
    window.setInterval(activateTab, 1000);
    function activateTab(){

       tabs.removeClass('active');
       var currentLink = tabs[counter];

       $('.tab-pane').removeClass('.active').hide();
       currentLink.addClass('active');
       $(currentLink.attr('href')).addClass('active').show();
       if(counter  < tabs.length)
         counter= counter + 1;
       else 
         counter = 0;
    }
});

but I've had no luck so far!

Any help would be much appreciated!


Solution

  • I saw your fiddle I came up with the solution using simple iteration JSFiddle Link Working

        $(function(){
        var count = 0;
        setInterval(function(){
        if(count == 1){
          $("ul>li:nth-child(4)>a").removeClass("active");
          $("ul>li:nth-child(1)>a").addClass("active");
          $("#first-tab").addClass("active show in");
          $("#fourth-tab").removeClass("active show in");
        }
        else if(count == 2){
          $("ul>li:nth-child(2)>a").addClass("active");
          $("ul>li:nth-child(1)>a").removeClass("active");
          $("#second-tab").addClass("active show in");
          $("#first-tab").removeClass("active show in");
        }
        else if(count == 3){
          $("ul>li:nth-child(3)>a").addClass("active");
          $("ul>li:nth-child(2)>a").removeClass("active");
          $("#third-tab").addClass("active show in");
          $("#second-tab").removeClass("active show in");
        }
        else if(count == 4){
          $("ul>li:nth-child(4)>a").addClass("active");
          $("ul>li:nth-child(3)>a").removeClass("active");
          $("#fourth-tab").addClass("active show in");
          $("#third-tab").removeClass("active show in");
        }
        if (count == 4){count=1;}else{count+=1}
      }, 10000);
    });