Reputation: 77
I am developing a jQuery website that has a top menu to navigate through div's. And i want it to stay on same tab that it was before refresh page.
Menu Code
<ul class="menu" id="menu">
<li class="menu-text"><h4>Title</h4></li>
<li class="current"><a href="#1" data-id="div1">Menu1</a></li>
<li><a href="#2" data-id="div2">Menu2</a></li>
<li><a href="#3" data-id="div3">Menu3</a></li>
</ul>
Content Div's
<div class="pbox" id="div1"> ... </div>
<div class="pbox" id="div2"> ... </div>
<div class="pbox" id="div3"> ... </div>
jQuery
var menu = $('#menu');
menu.on('click', 'a', function () {
var current = $(this).closest('li');
if(!current.hasClass("current")){
$('.current').removeClass('current');
current.addClass("current");
var id = $(this).attr('data-id');
$('.pbox:visible').hide(600);
$('#' + id + '.pbox').show(600);
history.pushState(null, null, '#' + id);
}
});
var menuId = location.hash.substring(1);
if (menuId) {
$(menu, "li a[data-id='" + menuId + "']").trigger('click');
}
The only problem is that when i refresh the page the URL still the same (if i was on second tab and i refresh the page, the link will be: index.php#2) but 'redirect' to first tab (#1).
Any sugestions?
Upvotes: 2
Views: 7200
Reputation: 874
First one is simpler and covered here: https://www.w3schools.com/jsref/prop_loc_hash.asp
function myFunction() {
location.hash = "part5";
var x = "The anchor part is now: " + location.hash;
document.getElementById("demo").innerHTML = x;
}
Second one you can find here: https://developer.mozilla.org/en/docs/Web/API/Window/localStorage Local storage way:
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
Upvotes: 3