0

In this case I have two pages in my localhost, home and projects.

Homepage - localhost, Projects page - localhost/projects/

The projects page has nav-tab from bootstrap 3:

    <ul class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a data-toggle="tab" href="#red">Red</a></li>
    <li><a data-toggle="tab" href="#orange">Orange</a></li>
    <li><a data-toggle="tab" href="#yellow">Yellow</a></li>
    <li><a data-toggle="tab" href="#green">Green</a></li>
    <li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="red">
        <h1>Red</h1>
        <p>red red red red red red</p>
    </div>
    <div class="tab-pane" id="orange">
        <h1>Orange</h1>
        <p>orange orange orange orange orange</p>
    </div>
    <div class="tab-pane" id="yellow">
        <h1>Yellow</h1>
        <p>yellow yellow yellow yellow yellow</p>
    </div>
    <div class="tab-pane" id="green">
        <h1>Green</h1>
        <p>green green green green green</p>
    </div>
    <div class="tab-pane" id="blue">
        <h1>Blue</h1>
        <p>blue blue blue blue blue</p>
    </div>
</div>

It works ok when i navigate through tabs inside the projects page, and if i hover on the tab "Orange" i can see the link - localhost/projects/#orange .

So the problem is that i want to access projects page and orange tab from the home page, but using this link will only open the localhost/projects/ and the first tab, in this case Red.

So my question is how do i make "nav-tab" accessible from outside the page.

Thanks in advance.

Giedrius
  • 603
  • 1
  • 6
  • 26

1 Answers1

0

When you load your projects page, you need to do 2 things: first, read the url and get what tab the user wants opened. Second, show that tab opened (and close the rest).

You can do the first part, reading the URL, in javascript with document.location.hash

And the second, opening the tab you want, is done by calling the Bootstrap method tab('show'). It closes any other. See explanation at Bootstrap documentation

@ZimSystem answered a previous question in a very clear manner here: https://stackoverflow.com/a/31003280/1414176 .

I copy here his code:

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;
});

@ZimSystem's second part is to clean the URL after the opening tab event is fired.

Edit: You have a better code in this other SO answer. It solves the scrollTo issue too.

// Javascript to enable link to tab
var hash = document.location.hash;
var prefix = "tab_";
if (hash) {
    $('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show');
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash.replace("#", "#" + prefix);
});
Community
  • 1
  • 1
Giuseppe
  • 464
  • 13
  • 24