Reputation: 360
There have been several SO solutions to this, but I haven't had any luck getting them to work. JQuery beginner trying to work through a solution to add an 'active' class to the active list item in a simple navigation menu:
<div id="main-menu">
<ul>
<li><a href="/site/about">About Us</a></li>
<li><a href="/site/work">Our Work</a></li>
<li><a href="/site/contact">Contact Us</a></li>
</ul>
</div>
A previous SO post indicated that this worked, but I've had no success so far. I'm using pretty permalinks in wordpress, so the full path to any page is like:
http://www.foobar.com/site/about/
This is my work so far:
<script>
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,''));
$('#main-menu li').each(function(){
if(urlRegExp.test(this.href)){
$(this).addClass('active');
}
});
});
</script>
I've tried several solutions, including changing how I write the href, etc. The part of the code I'm really foggy on is the urlRegExp part...Any help?
Upvotes: 3
Views: 20536
Reputation: 123428
try with
$('#main-menu li a').each(function(){
if(urlRegExp.test(this.href)){
...
});
instead of
$('#main-menu li').each(function(){
if(urlRegExp.test(this.href)){
...
});
since href
attribute you're looking on next line with this.href
is applied on links, and not on list-items
then, if you need to apply the class active
on <li>
element just use
$(this).parent().addClass('active');
// or $(this).closest('li').addClass('active');
// or pure-JS : this.parentNode.className += 'active';
Upvotes: 5
Reputation: 9167
this.href is wrong (should be $(this), plus you're checking on the list element, rather than li. Try this:
$('#main-menu li > a').each(function(){
if(urlRegExp.test($(this).attr('href'))){
$(this).addClass('active');
}
});
Upvotes: 2