9

I am working with bootstrap 3, and I am having some problems on linking a url to a specific tab, the panel changes but the activated tab doesnt. So I want the line <a href="#tab2" data-toggle="tab">link</a>, to go to the tab2, but it only goes to the panel of the tab2, it doesn't activate the tab.

Here is the html:

<div class="tabbable">
 <ul class="nav nav-tabs">
  <li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
  <li><a href="#tab2" data-toggle="tab">Section 2</a></li>
  <li><a href="#tab3" data-toggle="tab">Section 3</a></li>
 </ul>

 <div class="tab-content">
  <div class="tab-pane active" id="tab1">
     <p><a href="#tab2" data-toggle="tab">link</a>.</p>
  </div>

  <div class="tab-pane" id="tab2">
     <p> I'm in Section 2.</p>
  </div>

 <div class="tab-pane" id="tab3">
   <p>Howdy, I'm in Section 3 </p>
  </div>
 </div>
</div>

You can test this in this link http://bootply.com/90412

21

In order to activate the tab you can use jQuery plugin as shown in bootstrap. So you can add this piece of jQuery code to your program to enable the tab:

$(function () {
    $('#tab1 a').click(function (e) {
        e.preventDefault();
        $('a[href="' + $(this).attr('href') + '"]').tab('show');
    })
});

You can check this link: Updated code

|improve this answer|||||
0

Like Rohitha's answer, but a little more general:

$(function () {
  $('a.link-to-tab').click(function (e) {
    e.preventDefault();
    $('a[href="' + $(this).attr('href') + '"]').tab('show');
  })
});

Works for any anchor tag with class="link-to-tab" and an href to the tab id to be shown. For example, <a class="link-to-tab" href="#tab2">.

|improve this answer|||||
5

The activating of the tab depends of the ul structure. In your example case you could overwrite the click event of the plugin by adding to the end of your document (after Boostrap's Javascript):

$(function(){
    $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
    e.preventDefault()
    if($(this).parent().prop('tagName')!=='LI')
    {

        $('ul.nav li a[href="' + $(this).attr('href') + '"]').tab('show');
    }   
    else
    {
        $(this).tab('show')
    }
  })
});

Ref: Get element type with jQuery

Note: a shorter version will also work in this case:

$(function(){
    $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
    e.preventDefault()
    $('ul.nav li a[href="' + $(this).attr('href') + '"]').tab('show');
 })
 });
|improve this answer|||||
  • 1
    I like this one more, since it's working for all links!! ehmm I hope bootstrap implements this in next version! – azerafati Sep 11 '14 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.