最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bootstrap 4 remember tab - Stack Overflow

programmeradmin1浏览0评论

How can I get the browser to remember which tab the user was viewing when the page is refreshed or revisited ?

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
   <a class="nav-link active" data-toggle="tab" href="#home" role="tab" aria-controls="home">Home</a>

Profile Messages Settings

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

How can I get the browser to remember which tab the user was viewing when the page is refreshed or revisited ?

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
   <a class="nav-link active" data-toggle="tab" href="#home" role="tab" aria-controls="home">Home</a>

Profile Messages Settings

<div class="tab-content">
   <div class="tab-pane active" id="home" role="tabpanel">...</div>
   <div class="tab-pane" id="profile" role="tabpanel">...</div>
   <div class="tab-pane" id="messages" role="tabpanel">...</div>
   <div class="tab-pane" id="settings" role="tabpanel">...</div>
</div>
Share Improve this question asked Apr 27, 2017 at 12:34 SpunogSpunog 3091 gold badge3 silver badges11 bronze badges 3
  • Take a look at local storage. – krillgar Commented Apr 27, 2017 at 12:36
  • Or cookies. This isn't really specific to Bootstrap. – j08691 Commented Apr 27, 2017 at 12:39
  • Cool. Does anyone have code snippets on how to do that ? – Spunog Commented Apr 27, 2017 at 12:39
Add a comment  | 

5 Answers 5

Reset to default 12

This did the trick for me..

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  var hash = $(e.target).attr('href');
  if (history.pushState) {
    history.pushState(null, null, hash);
  } else {
    location.hash = hash;
  }
});

var hash = window.location.hash;
if (hash) {
  $('.nav-link[href="' + hash + '"]').tab('show');
}

Creates sharable links using the URL hash.

This is the multiple tabs example :

    $('a[data-toggle="tab"]').on('click', function (e) {

    var theTabId = $(this).attr('href');
    var activeTabs = (window.localStorage.getItem('activeTab') ? window.localStorage.getItem('activeTab').split(',') : []);

    var $sameLevelTabs = $(e.target).parents('.nav-tabs').find('[data-toggle="tab"]');

    $.each($sameLevelTabs, function (index, element) {
        var tabId = $(element).attr('href');
        if(theTabId != tabId && activeTabs.indexOf(tabId) !== -1){
            activeTabs.splice(activeTabs.indexOf(tabId), 1);
        }
    });

    //unique tabs
    if (activeTabs.indexOf($(e.target).attr('href')) === -1) {
        activeTabs.push($(e.target).attr('href'));
    }

    window.localStorage.setItem('activeTab', activeTabs.join(','));

});

var activeTabs = window.localStorage.getItem('activeTab');
if (activeTabs) {
    var activeTabs = (window.localStorage.getItem('activeTab') ? window.localStorage.getItem('activeTab').split(',') : []);
    $.each(activeTabs, function (index, element) {
        $('[data-toggle="tab"][href="' + element + '"]').tab('show');
    });
}

Here's one way you could do it. Obviously, this won't quite work since the snippet is on stackoverflow.com and the hash won't be appended to the url. I tested this locally though and it works.

Note: This will only work if you refresh the page or otherwise use the specific URL that refers to the tab to be opened. If you want it to "remember" the tab after you close the browser/tab or whatever, you would probably be best off using cookies or perhaps storing it in a database if you are dealing with client sessions.

//When the page loads, get the current # value and mark the li as "active" if the href attribute matches.
$(document).ready(function() {
  var v = "#" + window.location.hash.substr(1);
  $("#myTab li").each(function() {
    var href = $(this).children().first().attr("href");
    if (href == v) $(this).addClass("active");
    else $(this).removeClass("active");
  });
});

//Whenever we click on a li, remove all "active" classes and finally add "active" to the one we clicked.
$("#myTab li").on("click", function() {
  $("#myTab li").each(function() {
    $(this).removeClass("active");
  });
  $(this).addClass("active");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<ul class="nav nav-tabs" id="myTab">
  <li><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>

If you want to save a value for after refresh, You can use cookie or sessionStorage (as said in comments). The easier is sessionStorage i think.

$('.tab-pane').click(function(){
   sessionStorage.setItem("clicked", $(this).attr('id'));
});

And after page refresh, you can retrieve the saved value:

 if(sessionStorage.getItem("clicked") != null)
     var clickeId = sessionStorage.getItem("clicked")

I used local storage to store the active-tab-id and it works for me.

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

var activeTabId = localStorage.getItem("active-tab-id");
var activeTab = $(`a[href="${activeTabId}"]`);

if(activeTab.length == 1)
  activeTab.tab("show");
else
  $('a[data-toggle="tab"]')[0].click();

if your tab is not activated, by default it's clicked on the first tab.

发布评论

评论列表(0)

  1. 暂无评论