Reputation: 1384
I have this jquery code:
<script type="text/javascript">
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
});
</script>
and this HTML:
<div class="tab-box">
<a href="javascript:;" class="tabLink activeLink" id="companyinfo">Company</a>
<a href="javascript:;" class="tabLink" id="contacts">Contacts</a>
</div>
<div class="tabcontent" id="companyinfo-1">
content 1 here
</div>
<div class="tabcontent" id="contacts-1">
content 2 here
</div>
if the page is refreshed, the first tab is selected again. how can i make it remember my selection if the page is refreshed?
Upvotes: 1
Views: 1742
Reputation: 113455
You can save the index of the clicked tab in localStorage
.
// on click, save it in localStorage.selectedTab
localStorage.selectedTab = $(this).index() + 1;
// on document ready, after click handler was added search for it
if (localStorage.selectedTab) {
$(".tabLink:eq(" + (localStorage.selectedTab - 1) + ")").click();
}
Another solution would be using cookies, but I find localStorage easier.
Also, you can use the active
field in the tabs
API using, like Atakan Aral said:
$("#tabs").tabs({
activate: function( event, ui ) {
localStorage.selectedTab = ui.newTab.index() + 1;
},
active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});
Upvotes: 0
Reputation: 68
A more compact jQuery UI version of ionică-bizău's answer:
$("#tabs").tabs({
activate: function( event, ui ) {
localStorage.selectedTab = ui.newTab.index() + 1;
},
active: localStorage.selectedTab ? localStorage.selectedTab - 1 : 0
});
Upvotes: 3