Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 4 remember tab

Tags:

javascript

css

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>
like image 488
Spunog Avatar asked Nov 28 '22 22:11

Spunog


1 Answers

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.

like image 157
472084 Avatar answered Dec 09 '22 22:12

472084