Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking to a Bootstrap Tab from outside - how to set the tab to "active"?

I have a Bootstrap "tab" navigation with 3 different content tabs. It works perfectly except that I want to link to one of the tabs from OUTSIDE the tab navigation. Meaning that when someone clicks a link outside the tab window, it should set to "active" that tab and show the content.

Right now, it shows the content of that tab correctly, but the tab is not set to "active". How do I achieve this so that it should as "active" as if someone had clicked?

Here is the code:

<div>
<ul class="nav nav-tabs">
  <li class="active"><a href="#home" data-toggle="tab">Home</a></li>
  <li><a href="#profile" data-toggle="tab">Profile</a></li>
  <li><a href="#messages" data-toggle="tab">Messages</a></li>
</ul>
<div class="tab-content">
  <div class="tab-pane active" id="home">Home Content</div>
  <div class="tab-pane" id="profile">Profile Content</div>
  <div class="tab-pane" id="messages">Messages Content</div>
</div>
</div>

<p></p>

<a href="#profile" data-toggle="tab">Profile Link From Outside</a>

I made a jsFiddle to show it better: http://jsfiddle.net/fLJ9E/

Thank you very much for any help or hints :)

like image 588
user1227914 Avatar asked Nov 06 '13 14:11

user1227914


People also ask

How do I make Bootstrap tab active by default?

Answer: Use the HTML5 localStorage Object In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.

How do I open a Bootstrap tab with an external link?

Use url #hash es and open tabs based on the change of that value. This approach also have the advantage that the tabs will be directly linkable, so you could use e.g. example.com#sign-up to open a page with a specific tab opened.

How do you open a specific tab via an external link?

tab=x (where x=tab number) to the URL to display the specific tab. For example: https://demo.dj-extensions.com/dj-tabs/?tab=4 will open 4th tab on the demo site, you can try changing the number to another one to see how it works.

How do I create a tabbed navigation in Bootstrap?

Approach: To create a tabbed navigation menu, create a basic unordered list with list items as links. Then add classes nav and nav-tabs of bootstrap to unordered list and nav-items class to list items.


1 Answers

You can do a small trick to achieve this:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var target = this.href.split('#');
    $('.nav a').filter('[href="#'+target[1]+'"]').tab('show');
})

http://jsfiddle.net/s6bP9/

like image 137
claustrofob Avatar answered Oct 22 '22 18:10

claustrofob