8

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> 
Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
Vinay
  • 2,272
  • 4
  • 19
  • 34

1 Answers1

20

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');
}
Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • 1
    Thank you so much it works perfect for me. and also there is js that was causing problem. i changed js and it works perfect for me. – Vinay May 19 '18 at 13:44
  • https://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php – DeveloperDan Oct 28 '19 at 15:49