Bootstrap 3: Keep selected tab on page refresh
Bootstrap 3: Keep selected tab on page refresh
by Neil Bannet
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
<li><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#messages" data-toggle="tab">Messages</a></li>
<li><a href="#settings" data-toggle="tab">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">Contenido home</div>
<div class="tab-pane" id="profile">Contenido profile</div>
<div class="tab-pane" id="messages">Contenido messages</div>
<div class="tab-pane" id="settings">Contenido settings</div>
</div>
CSS
body {
padding: 15px;
}
JavaScript
jQuery(document).ready(function() {
jQuery('a[data-toggle="tab"]').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');
}
});