4

I'm developing a web page in which I'm using Twitter's Bootstrap Framework and their Bootstrap Tabs JS. It works great but I am trying to add extra links outside the tabs panel to open the tabs, it works fine clicking the tabs link under the ul --> li links.

But when I click a link outside the nav panel-tabs how can I have the tab panel switch and the active class added to the nav panel-tabs li CSS class element when clicking a link outside the nav panel itself (as the active class shows a different background color in my case).

For example:

These links are outside the panel code up the page:

<a href="page.php#gallery">Gallery</a>
<a href="page.php#movies">Movies</a>

I need to toggle the state of the tab class <ul class="nav panel-tabs"> --> <li> to active and remove it when the other links are clicked.

This is the panel with nav tabs:

<div class="panel-heading">
    <div class="padpanel">Panel Heading</div>
    <div class="pull-left">
        <ul class="nav panel-tabs">
            <li class="active"><a href="#profile" data-toggle="tab">Profile</a></li>
            <li><a href="#gallery" data-toggle="tab">Gallery</a></li>
            <li><a href="#movies" data-toggle="tab">Movies</a></li>
        </ul>
    </div>
</div>

<div class="panel-body">
    <div class="tab-content">
        <div class="tab-pane active" id="profile">Profile tab </div>
    </div>
</div>
<div class="panel-body">
    <div class="tab-content">
        <div class="tab-pane" id="gallery">Gallery tab </div>
    </div>
</div>
<div class="panel-body">
    <div class="tab-content">
        <div class="tab-pane" id="movies">Movies tab </div>
    </div>
</div>
Milad Rashidi
  • 1,296
  • 4
  • 22
  • 40
xop32
  • 93
  • 1
  • 4
  • 14
  • onloading, `$("a[href$='"+location.hash.slice(1)+"']").click()` . then your section selection should be persisted upon reloading, as well as being linkable. – dandavis Jun 22 '15 at 21:56

1 Answers1

7

You can use jQuery to get the page url #hash and select the Bootstrap tab...

var hash = document.location.hash;
if (hash) {
    $('.nav-tabs a[href='+hash+']').tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
});

Code: http://codeply.com/go/RypzN2UXKF

Demo (select tab 2): http://codeply.com/render/RypzN2UXKF#tab2

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • I had to change the code to $('.nav-tabs a[href="'+hash+'"]').tab('show'); to get it to work, was receiving a syntax error without the additional quotations. – No Window Dec 21 '16 at 21:33
  • This helped me with a project, but I have used vanilla JS like so: `if (document.location.hash) { document.querySelectorAll('ul.tabs li a[href="' + document.location.hash + '"]')[0].click(); }` – Ciprian Aug 01 '17 at 11:40