i have this html in my main navigation:
<div id="navigation">
<ul>
<li>
<a href="/contact">contact us</a>
</li>
<li>
<a href="/projects">projects</a>
</li>
</ul>
</div>
i wanted to mark the active link, so i use this jquery:
$("div#navigation").find("a[href='" + top.location.pathname + "']").each(function ()
{
$(this).addClass("active")
})
while its working good for URL's like domain.com/projects or domain.com/contacts,
i have a problem for deepers URL's, lets take for example domain.com/projects/proj-1.
i want that when i go to deeper URL, it will mark as active the parent URL (domain.com/projects). how can i do that?
Thanks!
First of all in your example you do not have to use the .each() method as you can directly assign the class like this
$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active")
For the problem use
$("div#navigation").find("a").filter(function(){
var href = $(this).attr('href');
return href!='/' && href !='#' && top.location.pathname.indexOf( href )==0 ;
}).addClass("active");
edit: made a small change to cater for the commented problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With