JQuery "active" class assignment for parent
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 need to mark the active link, so I use this jquery:
$("div#navigation").find("a[href='" + top.location.pathname + "']").each(function ()
{
$(this).addClass("active")
})
while it works well for URLs like domain.com/projects or domain.com/contacts,
I have a problem for deeper URLs, let's take domain.com/projects/proj-1 for example.
I want that when I go to a deeper URL, it will be marked as the active parent URL (domain.com/projects). How can i do this?
Thank!
+3
2 answers
First of all, in your example, you do not need to use a method .each(), since you can directly assign a class like this
$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active")
$("div#navigation").find("a").filter(function(){
var href = $(this).attr('href');
return href!='/' && href !='#' && top.location.pathname.indexOf( href )==0 ;
}).addClass("active");
edit: , .
+1
jQuery closest , .
$(this).closest("li","#navigation").addClass("active");
, , .
, , . :
$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active");
, :
$selected = $("div#navigation").find("a[href='" + top.location.pathname + "']");
$selected.addClass("active");
$selected.closest("li","#navigation").addClass("active");
0