Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep active tab on page refresh in bootstrap 4 using local storage?

I am trying to keep selected tab active on page refresh. but when i am not able to find any solution for tabs in bootstrap 4. i tried to make changes according to bootstrap 3 solutions but nothing work. please help me.

HTML

<ul class="nav my-nav1 nav-tabs mt-3 " id="myTab" role="tablist">
   <li class="nav-item border border-secondary rounded">
    <a class="nav-link active"  data-toggle="tab" href="#menu1">MENU1</a>
 </li>
 <li class="nav-item border border-secondary rounded">
   <a class="nav-link "  data-toggle="tab" href="#menu2">MENU2</a>
 </li>
</ul>

this is js i am using but it dosen't work.

JS

<script type="text/javascript">
  $(document).ready(function(){
  $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
    localStorage.setItem('activeTab', $(e.target).attr('href'));
  });
  var activeTab = localStorage.getItem('activeTab');
  if(activeTab){
    $('#myTab a[href="' + activeTab + '"]').tab('show');
  }
 });
</script> 
like image 286
Vinay Avatar asked May 19 '18 08:05

Vinay


People also ask

How do you keep the current tab active on page reload in bootstrap 4?

Answer: Use the HTML5 localStorage Object In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.

How do I make bootstrap tab active?

You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Adding the nav and nav-tabs classes to the tab ul will apply the Bootstrap tab styling, while adding the nav and nav-pills classes will apply pill styling.

How do you make a tab active by default?

Just add the class to your html. This will make the first tab active by default.


1 Answers

The jQuery selector is wrong: $('#myTab a[href="' + activeTab + '"]'), it should be...

$('.nav-tabs a[href="' + activeTab + '"]').tab('show');

https://www.codeply.com/go/C2B3mcrgSJ

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

var activeTab = localStorage.getItem('activeTab');
if(activeTab){
    $('.nav-tabs a[href="' + activeTab + '"]').tab('show');
}
like image 67
Zim Avatar answered Sep 19 '22 11:09

Zim