Reputation: 15374
This is a follow on from a previous question. What i want to achieve is to add a class to an li element after clicking an anchor tag which will render a new page. So i understand that when the page reloads new HTML is loaded and my addclass method will be forgotten.
So i have been looking into this and it seems as if there is still a way to do this with jquery? was hoping someone could perhaps clarify or let me know what is wrong with the following
So this is what i have.....
Navbar
<ul id="main-menu" class="clearfix sf-js-enabled sf-arrows">
<li>
<a href="/"><i class="icon-home"></i> Home</a>
</li>
<li>
<a href="/pages/aboutme"><i class="icon-desktop"></i> About Me</a>
</li>
<li>
<a href="/pages/portfolio"><i class="icon-picture"></i> Portfolio</a>
</li>
<li>
<a href="/blog"><i class="icon-comments"></i> Blog</a>
</li>
<li>
<a href="/contact"><i class="icon-envelope"></i> Contact</a>
</li>
</ul>
Jquery
$('#main-menu li').each(function() {
var href = $(this).find('a').attr('href');
if (href === window.location.pathname) {
$(this).addClass('current-menu-item');
}
});
Though this isnt working. Could anyone please explain why? or see an error in the code, my initial thoughts that are i need to find the a closest to the current li ?
Any help appreciated
Thanks
Upvotes: 0
Views: 133
Reputation: 165
Well if you take href from an a tag, maybe you should take href also from page? if (href === window.location.href)
Anyway I am pretty sure the problem is in the if condition.
Upvotes: 0
Reputation: 5826
Just put 1 line after href variable.
console.log(href)
You will understand easily what is going wrong there. You need to see this in console. if you are not aware with this then use following.
alert(href)
Upvotes: 2