139

I am trying to keep selected tab active on refresh with Bootstrap 3. Tried and checked with some question already been asked here but none of work for me. Don't know where I am wrong. Here is my code

HTML

<!-- tabs link -->
<ul class="nav nav-tabs" id="rowTab">
    <li class="active"><a href="#personal-info" data-toggle="tab">Personal Information</a></li>
    <li><a href="#Employment-info" data-toggle="tab">Employment Information</a></li>
    <li><a href="#career-path" data-toggle="tab">Career Path</a></li>
    <li><a href="#warnings" data-toggle="tab">Warning</a></li>
</ul>
<!-- end: tabs link -->

<div class="tab-content">
    <div class="tab-pane active" id="personal-info">
        tab data here...
    </div>

    <div class="tab-pane" id="Employment-info">
        tab data here...
    </div>

    <div class="tab-pane" id="career-path">
        tab data here...
    </div>

    <div class="tab-pane" id="warnings">
        tab data here...
    </div>
</div>

Javascript:

// tab
$('#rowTab a:first').tab('show');

//for bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//save the latest tab; use cookies if you like 'em better:
localStorage.setItem('selectedTab', $(e.target).attr('id'));
});

//go to the latest tab, if it exists:
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab) {
  $('#'+selectedTab).tab('show');
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
Code Lover
  • 8,099
  • 20
  • 84
  • 154
  • The reason it's not working is because , it's not storing the selected tab. When i did `console.log("selectedTab::"+selectedTab);`, I got : `selectedTab::undefined` . So the logic you applied is not correct – The Dark Knight Sep 25 '13 at 08:14
  • So can you please guide me what to do? – Code Lover Sep 25 '13 at 08:20
  • I think this will work : http://jsbin.com/UNuYoHE/2/edit . If it does let me know, then i will post the answer in a crisp manner. You might also wanna look at the div tab texts. they do not give the proper response when you click them. For eg, if you click tab4, you get tab1 text. – The Dark Knight Sep 25 '13 at 08:38
  • BTW , i used this answer for the JS coding : http://stackoverflow.com/questions/9529723/jquery-tool-keep-selected-tab-on-refresh-or-save-data – The Dark Knight Sep 25 '13 at 08:41
  • Thanks, it is not working and going back to the first tab. Yes I have refereed that answer..but didn't work.. :( – Code Lover Sep 25 '13 at 08:50
  • The selector for bootstrap3 should be `$("ul.nav-tabs > li > a")`. I agree that the current selector also works. However, the bootstrap3 doc does foresee `data-toggle="tab"` anymore. – koppor Sep 25 '13 at 20:23
  • The question is a duplicate of http://stackoverflow.com/q/10523433/873282 – koppor Sep 26 '13 at 11:27
  • @koppor but that answer didn't helped at all – Code Lover Sep 26 '13 at 12:38

19 Answers19

211

I prefer storing the selected tab in the hashvalue of the window. This also enables sending links to colleagues, who than see "the same" page. The trick is to change the hash of the location when another tab is selected. If you already use # in your page, possibly the hash tag has to be split. In my app, I use ":" as hash value separator.

<ul class="nav nav-tabs" id="myTab">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home">home</div>
  <div class="tab-pane" id="profile">profile</div>
  <div class="tab-pane" id="messages">messages</div>
  <div class="tab-pane" id="settings">settings</div>
</div>

JavaScript, has to be embedded after the above in a <script>...</script> part.

$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
koppor
  • 19,079
  • 15
  • 119
  • 161
  • In the script section, you should add a semi-colon to the end of `e.preventDefault();` and `$(this).tab('show');` – Sean Adams-Hiett Jan 29 '14 at 00:28
  • it shown me two errors `TypeError: a.browser is undefined` and `TypeError: $(...).tab is not a function`. can you tell me which jquery files are needed. – UdayKiran Pulipati Feb 25 '14 at 05:12
  • Here it works with latest jQuery and latest Bootstrap. Be sure to load the JavaScript part of bootstrap, too. HTML5 skeletton at http://liveweave.com/k7QRvy. Click on tabs does NOT work there, but at least tabs are rendered. You can copy the source at the top left input field and paste it as `test.html`. With a running internet connection, it works perfectly. – koppor Feb 26 '14 at 10:38
  • Great answer! Works perfectly. However, I have a mix of dropdown tabs and normal tabs. So the 'ul.nav-tabs > li > a' does not work across them. Easier to associate a class at the final level to ensure that any level of tab nesting works. – Saurabh Hirani Mar 13 '14 at 09:39
  • Using `.nav-tabs` instead of id would generalize it to use for all bootstrap tabs (not tested). – Sisir Mar 31 '14 at 06:40
  • @koppor i added a link button ` click me`.When i click on the link button, after the postback event the browser display the default tab instead of the current tab. – Djama Apr 15 '14 at 07:14
  • @SeanAdams-Hiett node's standard states that semicolons are so 2000 and not hip any more: https://github.com/feross/standard – koppor Jun 19 '15 at 08:57
  • 13
    Unfortunately the browser is jumping to the tab content when you click on it. This is the default behavior when you set the window.location.hash value. An alternative might be using push.state but you need a polyfill for IE<=9. For more infos and other alternative solutions take a look at http://stackoverflow.com/questions/3870057/how-can-i-update-window-location-hash-without-jumping-the-document – Philipp Michael Jul 07 '15 at 08:21
  • 3
    Is there any way to prevent the "fake scroll" to the id in question when we click on the element? – Patrice Poliquin Dec 12 '16 at 19:59
  • 1
    The scroll is because of the id assigned to the tab pages. If you use semantic IDs and mangle the hash (i.e. add prefix/suffix) it will not be recognized as a valid id and no scroll will happen. Will expand the answer with this. – Alex Mazzariol Jul 13 '17 at 13:33
  • 1
    @koppor it works but when I jump directly on the other saved tab(via link) it displays the home tab or first tab quickly around 1 second before it jumps to the tab in the link.. Any idea to prevent it from displaying the first tab since it is not needed? – mboy Mar 12 '19 at 06:19
  • @mboy add class `active in` using jquery. for first tab on url or hash base. – wasimv09 Mar 19 '19 at 10:29
  • You safe my life. Better if you use `redirect` technique as mentioned in this link https://www.semicolonworld.com/question/51779/redirect-back-to-a-specific-tab-pane-in-laravel – Sead Lab May 30 '20 at 14:20
140

This is the best one that I tried:

$(document).ready(function() {
    if (location.hash) {
        $("a[href='" + location.hash + "']").tab("show");
    }
    $(document.body).on("click", "a[data-toggle='tab']", function(event) {
        location.hash = this.getAttribute("href");
    });
});
$(window).on("popstate", function() {
    var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
    $("a[href='" + anchor + "']").tab("show");
});
Jonathan
  • 6,741
  • 7
  • 52
  • 69
Xavi Martínez
  • 2,125
  • 1
  • 16
  • 17
  • it will keep refresh when I clicked a selector box or textbox – Rei Tee Sep 29 '15 at 07:40
  • 1
    I think changing the selector to `"a[data-toggle=tab]"` would be better. The way the selector is written now it also changes the browser URL when clicking on a link to for instance open a modal. – leifdenby Oct 25 '15 at 21:53
  • Nice solution, but the page keeps flickering on tab change, which is not what I need. Tabs are populated with AJAX, maybe that might be issue? – jeesus Dec 02 '15 at 07:51
  • 5
    You may want to add string bracket on the selector, like 'a[href="' + location.hash + '"]' . Stumbled upon a syntax error. – asdacap Feb 02 '16 at 10:16
  • Works perfect. I found another variant with local storage: http://stackoverflow.com/a/10524697/812915 – equiman Apr 09 '16 at 22:35
  • How do I use this in my angular template? – shanti Dec 26 '17 at 07:37
  • 1
    Using this as-is conflicted with Bootstrap dropdowns (which use `data-toggle="dropdown"` and which I happen to have on the same page with tabs in one case. Like someone suggested here, just replacing `$(document.body).on("click", "a[data-toggle]", function(event) {` with `$(document.body).on("click", "a[data-toggle='tab']", function(event) {` did the trick for me. – Jiveman Jun 12 '18 at 05:58
  • Works except in the case of multiple embedded tabs – Jonathan May 23 '19 at 21:13
  • Jumps for some reason everytime I click a tab :( – Jonathan May 23 '19 at 22:36
51

A mix between others answers:

  • No jump on click
  • Save on location hash
  • Save on localStorage (e.g: for form submit)
  • Just copy&paste ;)

    if (location.hash) {
      $('a[href=\'' + location.hash + '\']').tab('show');
    }
    var activeTab = localStorage.getItem('activeTab');
    if (activeTab) {
      $('a[href="' + activeTab + '"]').tab('show');
    }
    
    $('body').on('click', 'a[data-toggle=\'tab\']', function (e) {
      e.preventDefault()
      var tab_name = this.getAttribute('href')
      if (history.pushState) {
        history.pushState(null, null, tab_name)
      }
      else {
        location.hash = tab_name
      }
      localStorage.setItem('activeTab', tab_name)
    
      $(this).tab('show');
      return false;
    });
    $(window).on('popstate', function () {
      var anchor = location.hash ||
        $('a[data-toggle=\'tab\']').first().attr('href');
      $('a[href=\'' + anchor + '\']').tab('show');
    });
    
insign
  • 5,353
  • 1
  • 38
  • 35
  • 4
    Best solution I've tried from many different. The jumping to the tab content was annoying – kentor Jun 14 '17 at 19:36
  • 4
    Content jump is still there with this answer – Shahbaz A. Aug 31 '17 at 07:50
  • 2
    Found a caveat to this - the tab stored in local storage will override one in the location hash, which makes it difficult to follow links if the page has already been visited. I've updated thus: `var activeTab = localStorage.getItem('activeTab'); if (location.hash) { $('a[href=\'' + location.hash + '\']').tab('show'); } else if (activeTab) { $('a[href="' + activeTab + '"]').tab('show'); }` – Gary Stanton Sep 15 '17 at 11:46
  • 1
    I wonder why this doesn't work to me.. Should I replace something in this code and not just literaly copy and paste? :) – mboy Mar 12 '19 at 06:54
  • Does not work for me. If I click a tab and refresh, nothing. Other solutions work however – Jonathan May 23 '19 at 22:50
  • 1
    To get this to work, you have to either put this script AFTER your tabs, OR, wrap the first clause (two ifs + var dec) in `$(document).ready(function() {` because your tabs don't exist yet and it tries to slam the active tab before they are loaded – Jonathan May 23 '19 at 22:54
  • This is the best, working even with form submit returns.. and backward compatible with copy & paste... ;) – sarath Jul 27 '20 at 21:55
27

Xavi's code was allmost fully working. But when navigating to another page, submitting a form, then being redirected to the page with my tabs was not loading the saved tab at all.

localStorage to the rescue (slightly changed Nguyen's code):

$('a[data-toggle="tab"]').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
});

$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
    var id = $(e.target).attr("href");
    localStorage.setItem('selectedTab', id)
});

var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
    $('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
xfscrypt
  • 16
  • 5
  • 28
  • 59
  • 2
    This is gold! It works even with modals! Great answer. – Lech Osiński Jan 25 '17 at 14:45
  • 3
    This code is fantastic, and works great if you want the tab to remain selected even if the user leaves the site (ends the session) and comes back later. To have the selection persist only for the during the current session and return to the default tab on the next session, replace the two instances of "localStorage" with "sessionStorage". – Gary.Ray Mar 08 '17 at 22:00
  • Short, sweet, copy/paste solution that works great with Bootstrap 4. – Apps-n-Add-Ons Feb 10 '18 at 16:22
  • 1
    `[data-toggle="pill"]` for pills – mxmissile Jan 29 '19 at 18:49
17

This one use HTML5 localStorage to store active tab

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
   $('#navtab-container a[href="' + activeTab + '"]').tab('show');
}

ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

Community
  • 1
  • 1
Ajith R Nair
  • 2,170
  • 1
  • 15
  • 10
  • this is nice, but a disadvantage is you wouldn't be able to share links with active tab – random-forest-cat Apr 13 '16 at 18:30
  • 1
    this is nice, the advantage is it does not introduce issue where "window.location.hash" adding hash value to http request param in the url causing collision and bad param read by other http request such as pagination, and etc. – Dung Apr 27 '16 at 22:01
6

Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.

<script type="text/javascript">
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    var activeTab = localStorage.getItem('activeTab');
    if(activeTab){
        $('#myTab a[href="' + activeTab + '"]').tab('show');
    }
});
</script>

and here is the code for bootstrap tabs:

<div class="affectedDiv">
    <ul class="nav nav-tabs" id="myTab">
        <li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
        <li><a data-toggle="tab" href="#sectionB">Section B</a></li>
        <li><a data-toggle="tab" href="#sectionC">Section C</a></li>
    </ul>
    <div class="tab-content">
        <div id="sectionA" class="tab-pane fade in active">
            <h3>Section A</h3>
            <p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
        </div>
        <div id="sectionB" class="tab-pane fade">
            <h3>Section B</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
        <div id="sectionC" class="tab-pane fade">
            <h3>Section C</h3>
            <p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
        </div>
    </div>
</div>


Dont forget to call the bootstrap and other fundamental things 

here are quick codes for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


Now let's come to the explanation:

The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.

Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/

I wish my answer could help you all.. Cheerio! :)

Mr. Winson
  • 61
  • 1
  • 2
5

Basing myself on answers provided by Xavi Martínez and koppor I came up with a solution that uses the url hash or localStorage depending on the availability of the latter:

function rememberTabSelection(tabPaneSelector, useHash) {
    var key = 'selectedTabFor' + tabPaneSelector;
    if(get(key)) 
        $(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');

    $(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
        set(key, this.getAttribute('href'));
    }); 

    function get(key) {
        return useHash ? location.hash: localStorage.getItem(key);
    }

    function set(key, value){
        if(useHash)
            location.hash = value;
        else
            localStorage.setItem(key, value);
    }
}

Usage:

$(document).ready(function () {
    rememberTabSelection('#rowTab', !localStorage);
    // Do Work...
});

It does not keep up with the back button as is the case for Xavi Martínez's solution.

Community
  • 1
  • 1
Ziad
  • 1,036
  • 2
  • 21
  • 31
5

My code, it work for me, I use localStorage HTML5

$('#tabHistory  a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href");
  localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');
Igor Ivancha
  • 3,413
  • 4
  • 30
  • 39
Nguyen Pham
  • 51
  • 1
  • 2
5

I tried this and it works:

    jQuery(document).ready(function() {
        jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
            localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
        });

        // Here, save the index to which the tab corresponds. You can see it 
        // in the chrome dev tool.
        var activeTab = localStorage.getItem('activeTab');

        // In the console you will be shown the tab where you made the last 
        // click and the save to "activeTab". I leave the console for you to 
        // see. And when you refresh the browser, the last one where you 
        // clicked will be active.
        console.log(activeTab);

        if (activeTab) {
           jQuery('a[href="' + activeTab + '"]').tab('show');
        }
    });

I hope it would help somebody.

Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/37/

Nobody
  • 360
  • 6
  • 9
2

Since I cannot comment yet I copied the answer from above, it really helped me out. But I changed it to work with cookies instead of #id so I wanted to share the alterations. This makes it possible to store the active tab longer than just one refresh (e.g. multiple redirect) or when the id is already used and you don't want to implement koppors split method.

<ul class="nav nav-tabs" id="myTab">
    <li class="active"><a href="#home">Home</a></li>
    <li><a href="#profile">Profile</a></li>
    <li><a href="#messages">Messages</a></li>
    <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
    <div class="tab-pane active" id="home">home</div>
    <div class="tab-pane" id="profile">profile</div>
    <div class="tab-pane" id="messages">messages</div>
    <div class="tab-pane" id="settings">settings</div>
</div>

<script>
$('#myTab a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
    var id = $(e.target).attr("href").substr(1);
    $.cookie('activeTab', id);
});

    // on load of the page: switch to the currently selected tab
    var hash = $.cookie('activeTab');
    if (hash != null) {
        $('#myTab a[href="#' + hash + '"]').tab('show');
    }
</script>
  • Thanks for the update. In reality I was looking for such resolution but than the time I wanted I got only @koppor answer as working one. In fact that is one of the great way to if we want to use back feature. Thanks for the update – Code Lover Dec 11 '15 at 16:27
2

I tried the code offered by Xavi Martínez. It worked but not for IE7. The problem is - tabs don't refer to any relevant content.
So, I prefer this code for solving that problem.

function pageLoad() {
  $(document).ready(function() {

    var tabCookieName = "ui-tabs-1"; //cookie name
    var location = $.cookie(tabCookieName); //take tab's href

    if (location) {
      $('#Tabs a[href="' + location + '"]').tab('show'); //activate tab
    }

    $('#Tabs a').click(function(e) {
      e.preventDefault()
      $(this).tab('show')
    })

    //when content is alredy shown - event activate 
    $('#Tabs a').on('shown.bs.tab', function(e) {
      location = e.target.hash; // take current href
      $.cookie(tabCookieName, location, {
        path: '/'
      }); //write href in cookie
    })
  });
};
Community
  • 1
  • 1
Vitalii Isaenko
  • 941
  • 1
  • 14
  • 37
1

In addition to Xavi Martínez's answer avoiding the jump on click

Avoiding Jump

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    $('a[href=' + anchor + ']').tab('show');
});

Nested tabs

implementation with "_" character as separator

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        var tabs = location.hash.substring(1).split('_');

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });         

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        var tabs = location.hash.substring(1).split('_');

        //console.log(tabs);

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    var tabs = anchor.substring(1).split('_');

    $.each(tabs,function(n){

        $('a[href=#' + tabs[n] + ']').tab('show');
    });

    $('a[href=' + anchor + ']').tab('show');
});
RafaSashi
  • 16,483
  • 8
  • 84
  • 94
1

Thanks for sharing.

By reading all the solutions. I came up with a solution that uses the url hash or localStorage depending on the availability of the latter with below code:

$(function(){
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    })

    var hash = window.location.hash;
    var activeTab = localStorage.getItem('activeTab');

    if(hash){
          $('#project-tabs  a[href="' + hash + '"]').tab('show');   
    }else if (activeTab){
        $('#project-tabs a[href="' + activeTab + '"]').tab('show');
    }
});
Vaibhav
  • 858
  • 10
  • 13
1

There is a solution after reloading the page and keeping the expected tab as selected.

Suppose after saving data the redirected url is : my_url#tab_2

Now through the following script your expected tab will remain selected.

$(document).ready(function(){
    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
        $('.nav-tabs a').removeClass('active');
    }
});
Hasib Kamal Chowdhury
  • 2,476
  • 26
  • 28
1

For Bootstrap v4.3.1. Try below:

$(document).ready(function() {
    var pathname = window.location.pathname; //get the path of current page
    $('.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
})
gkc123
  • 512
  • 1
  • 7
  • 24
0

Using html5 I cooked up this one:

Some where on the page:

<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>

The viewbag should just contain the id for the page/element eg.: "testing"

I created a site.js and added the scrip on the page:

/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
  function() {
    var setactive = $("#heading").data("activetab");
    var a = $('#' + setactive).addClass("active");
  }
)

Now all you have to do is to add your id's to your navbar. Eg.:

<ul class="nav navbar-nav">
  <li **id="testing" **>
    @Html.ActionLink("Lalala", "MyAction", "MyController")
  </li>
</ul>

All hail the data attribute :)

Igor Ivancha
  • 3,413
  • 4
  • 30
  • 39
0

We used jquery trigger to onload have a script hit the button for us

$(".class_name").trigger('click');

Dan Kaiser
  • 991
  • 8
  • 7
0

There's so many ways to do this. I came up with this, short and simple.

  var url = document.location.toString();
  if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
  } 

  $('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
    if(e.target.hash == "#activity"){
      $('.nano').nanoScroller();
    }
  })
halfer
  • 19,824
  • 17
  • 99
  • 186
user752746
  • 617
  • 9
  • 31
0

In the setTab function I have received class name as a params form tab and saved it in local storage. In document ready function I checked that active class exist or not. if exist I set that tab as active or set basic tab as active

$(document).ready(function() {
   var activeTab = localStorage.getItem('activeTab');
   if (activeTab) {
      $('#v-pills-'+activeTab+'-tab').addClass('active');
      $('#v-pills-'+activeTab).addClass('show active');
   } else {
      $('#v-pills-basic-tab').addClass('active');
      $('#v-pills-basic').addClass('show active');
   }
})

function setTab(params) {
  localStorage.setItem('activeTab', params);
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31