I have two questions for my code.
First: I want to keep last selected tab active after page refresh. Issue is when page refreshs the first tab is always active.
Second: When a user comes at this page by the link change password. At this time I want to make second(change password) tab active.
Here my code:
<ul class="tab">
<li class="current" data-tab="tab1">Account information</li>
<li data-tab="tab2">Change Password</li>
</ul>
<div class="tab-content current" id="tab1">
Tab1 Content comes Here!
</div>
<div class="tab-content" id="tab2">
Tab1 Content comes Here!
</div>
<script src="js/jquery-1.12.4.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('ul.tab li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tab li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
});
});
</script>
You can save it to localStorage:
$(document).ready(function() {
var last_id = localStorage.getItem('tab_id');
if (last_id) {
$('ul.tab li').removeClass('current');
$('.tab-content').removeClass('current');
$(".tab li").eq(last_id.match(/\d+/)[0]-1).addClass('current');
$("#" + last_id).addClass('current');
}
$('ul.tab li').click(function() {
var tab_id = $(this).attr('data-tab');
$('ul.tab li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#" + tab_id).addClass('current');
localStorage.setItem('tab_id', tab_id);
});
});
Here is the working example: https://jsfiddle.net/k5j9qv4k/2/
As for second question, I am assuming you are not in this page which has tabs. Then you can save tab_id='tab2'
to localStorage:
<a href="pageurl" onclick="localStorage.setItem('tab_id', 'tab2');">change password</a>
Use sessionStorage to store which tab is active and apply current class to active tab. Session storage variable still persists after page refresh.
This might help.
$(document).ready(function(){ if(localStorage.getItem("CURRENT_TAB")=="tab2"){ var x=$("li.tab2"); $("li").not(x).removeClass("current"); x.addClass("current"); } $(".tab li").click(function(){ if($(this).hasClass("tab2")){ localStorage.setItem("CURRENT_TAB","tab2"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="tab"> <li class="current tab1">TAB 1</li> <li class="tab2">TAB 2</li> </ul>
You can do using local storage. Write below code in your tab page.
$('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
localStorage.setItem('currentActiveTab', $(e.target).attr('href'));
});
var currentActiveTab = localStorage.getItem('currentActiveTab');
if(currentActiveTab){
$('#TABID a[href="' + currentActiveTab+ '"]').tab('show');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.