Bootstrap 3: Keep selected tab on page refresh

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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

回答1:

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


回答2:

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]", 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"); });


回答3:

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


回答4:

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


回答5:

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



回答6:

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.



回答7:

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


回答8:

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>


回答9:

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


回答10:

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


回答11:

I tried this and it works: ( Please replace this with the pill or tab you are using )

    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/5/



回答12:

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>        
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!