简体   繁体   中英

Using jQuery to automate Bootstrap dynamic tabs

I have the following code for a set of dynamic bootstrap tabs:

<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#home">Me</a></li>
<li><a data-toggle="tab" href="#menu1">AAA</a></li>
<li><a data-toggle="tab" href="#menu2">BBB</a></li>
<li><a data-toggle="tab" href="#menu3">CCC</a></li>
</ul>

<div class="tab-content">
<div id="home" class="tab-pane fade in active">
  <h3><u>Me</u></h3>
  <p>Content</p>
</div>
<div id="menu1" class="tab-pane fade">
  <h3><u>AAA</u></h3>
  <p>content</p>
</div>
<div id="menu2" class="tab-pane fade">
  <h3><u>BBB</u></h3>
  <p>content</p>
</div>
<div id="menu3" class="tab-pane fade">
  <h3><u>ccc</u></h3>
  <p>content</p>
</div>

I want to know if there's a jquery that will automate them after say, 5 seconds to shift to the next tab then revert back to the beginning and loop?

Here is a small script the might give you an idea:

var i = 0;
setInterval(function(){
  var content = $(".tab-pane");
  var menu = $(".nav-tabs li");
  var prev = (i%(content.length))-1;
  var curr = i%(content.length);
  if(curr != 0){
    $(menu[prev]).removeClass("active");
    $(menu[curr]).addClass("active");
    $(content[prev]).removeClass("in active");
    $(content[curr]).addClass("in active");
  }else{
    $(menu[menu.length-1]).removeClass("active");
    $(menu[0]).addClass("active");
    $(content[content.length-1]).removeClass("in active");
    $(content[0]).addClass("in active");
  }
  i++;
},1000);

Working fiddle : https://jsfiddle.net/mt9n1dbs/

Update:

I actually got a better solution for this:

var i = 0;
setInterval(function(){
  var menu = $(".nav-tabs li");
  var curr = i%(menu.length);
  if(curr != 0){
    $(".nav-tabs > .active").next('li').find('a').trigger('click');
  }else{
    $(menu[0]).find('a').trigger('click');
  }
  i++;
},1000);

Working fiddle 2 : https://jsfiddle.net/mt9n1dbs/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM