Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap linking to a tab with an url

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

like image 598
MariaZ Avatar asked Oct 28 '13 00:10

MariaZ


2 Answers

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

like image 200
Rohitha Avatar answered Nov 01 '22 00:11

Rohitha


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');
 })
 });
like image 40
Bass Jobsen Avatar answered Nov 01 '22 01:11

Bass Jobsen