Search code examples
twitter-bootstrap-3tabsnav-pills

change active tab on document ready


I would like to change the active pill/tab on document load. I know you can set the active pill like I have below but for other reasons I want to change it after document load. I have tried various bits of JS but nothing seems to work. Here's the HTML and JS (I have also tried replacing data-toggle="pill" with data-toggle="tab" below and still doesn't work).

<div>  
  <ul class="nav nav-pills pillstyle">
    <li class="active tabstyle"><a data-toggle="pill" href="#apple">Apple</a></li>
    <li class="tabstyle"><a data-toggle="pill" href="#banana">Banana</a></li>
    <li class="tabstyle"><a data-toggle="pill" href="#pear">Pear</a></li>
    <li class="tabstyle"><a data-toggle="pill" href="#orange" >Orange</a></li>
  </ul>
</div>  <!-- nav pills close -->

<div class="tab-content">      
  <div id="apple" class="tab-pane fade in active"> `
 .... content of tabs.

JS

$(document).ready(function(){
$('#banana').tab('show');
});

or

 $(document).ready(function(){
 $('#banana').pill('show');
 });

Solution

  • You just need to change your jQuery selector to address the a element instead of the tab-pane div.

    $(document).ready(function(){
        $('a[href="#banana"]').tab('show');
    });
    

    If you need, you can find more detailed description about bootstrap tabs in the official documentation.