How to remember and save active nav tab with bootstrap 3? (Asp Mvc 5 if it matters)

Using bootstrap 3 I am trying to use this exameple. It works fine as expected, the first tab is active when the page is displayed. However, when I navigate to another page in my application and then return to that page, it forgets the active tab, always the first tab is active.

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

What I've tried so far: I tried to keep class = "active" from the li element and class = "on the active" part from the div element. Unfortunately this case doesn't display any tabs at all, the user has to explicitly click on the navigation to display any tab, so this doesn't seem like a 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>

      

+3


source to share


1 answer


You actually store this information in your url.

If your original url of this page is "//foo.bar/example" you can extend these three urls

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


When the 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 a frontend framework like backbone or angular, they have built-in routing support that makes things easier for you.

The advantage of this over cookies / localStorage is that you can send these URLs to other people and they will be sent to the exact tab specified.

0


source







All Articles