g.pickardou
g.pickardou

Reputation: 35873

How to remember and keep the active nav tab using bootstrap 3? (Asp Mvc 5 if this matters)

Using bootstrap 3 I am trying this exameple. It works fine as expected, the first tab is active when page is shown. However when I navigate to an other page in my app, then back to this page, it forget the active tab, always the first tab is the active.

I would like to the page remember what was the active tab.

What I was tried so far: I've tried to leave the class="active" from the li element and the class="in active" part from the div element. Unfortunately this case no tabs displayed at all, the user must explicitly click on the nav to show any tab, so this does not seems to be the solution.

Thanks in advance.

<ul class="nav nav-tabs">
    <li class="active"><a href="#graduation" data-toggle="tab">graduation</a></li>
    <li><a href="#graduate" data-toggle="tab">graduate</a></li>
    <li><a href="#extension" data-toggle="tab">extension</a></li>
</ul>
<div class="tab-content" id="TabContent">
    <div class="tab-pane fade" id="graduation">
        <p>
            anything
        </p>
    </div>
    <div class="tab-pane fade in active" id="graduate">
        <p>
            graduate
        </p>
    </div>
    <div class="tab-pane fade" id="extension">
        <p>
            extension
        </p>
    </div>
</div>

Upvotes: 3

Views: 1180

Answers (1)

xiamx
xiamx

Reputation: 7030

You actually store this information in your url.

If your original url to this page is "//foo.bar/example", then you can extended to these three urls

  • //foo.bar/example#graduation
  • //foo.bar/example#graduate
  • //foo.bar/example#textension

When user clicks on a tab, you can update the url, and when your page loads, you can use window.location.hash to get the hash fragment and use the hash fragment to activate the corresponding tab.

If you are using some frontend framework like backbone or angular, they have builtin routing support that makes things easier for you.

Advantage of this over cookies/localStorage is that you can send these urls to other people, and they will be taken to the exact tab indicated.

Upvotes: 0

Related Questions