Reputation: 9247
So i have this navigation on my header but problem is when i click on link and redirect me to that page it lose active class. Any suggestion?
<nav>
<div class="menu-topmenu-container">
<ul id="menu-topmenu" class="menu">
<li id="whats-on" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-53">
<a href="#whatson" class="active">What’s On</a>
</li>
<li id="menu-item-52" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-52">
<a href="visiting-us">Visiting Us</a>
</li>
<li id="menu-item-46" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-33 current_page_item menu-item-46">
<a href="collections-research">Collections & Research</a>
</li>
<li id="menu-item-50" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-50">
<a href="learning">Learning</a>
</li>
<li id="menu-item-49" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-49">
<a href="get-involved">Get Involved</a>
</li>
</div>
</nav>
This is my script:
jQuery(function($){
$('nav ul li a').on('click', function () {
$(this).closest('nav ul').find('a.active').removeClass('active');
$(this).addClass('active');
});
});
Upvotes: 0
Views: 1592
Reputation: 21487
That is because when you click on the link, you go to a different page.
Not tested, and just wrote this now, but something like this:
$(function(){
var href=window.location.href;
$('nav a').each(function(e,i){
if (href.indexOf($(e).attr('href'))>=0)
{
$(e).addClass('active');
}
});
});
You can also use data-attributes instead of href to do a comparison, which will likely be somewhat easier, and more customizable to handle odd situations like the index page. Of course, since you are getting the html from the server, you could just have the server put the active class on the appropriate link as well.
Upvotes: 4
Reputation: 20987
It seems like your probably navigating to a new page you should store the id in local storage like this:
$('body').on('click', 'nav ul li a' , function () {
$(this).closest('nav ul').find('a.active').removeClass('active');
localStorage.setItem('lastActiveId', $(this).attr('id'));
});
then on load you need to set it
$(function () {
var lastId = localStorage.getItem('lastActiveId', $(this).attr('id'));
//check if defined
if(!!lastId)
{
$('#' + lastId).addClass('active');
}
});
Upvotes: 1