eran
eran

Reputation: 119

jQuery “active” class assignment for the 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 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!

Upvotes: 3

Views: 969

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

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

Upvotes: 1

Keltex
Keltex

Reputation: 26426

You can use jquery's closest operator to walk up the tree and mark all parent lis. Like this

$(this).closest("li","#navigation").addClass("active");    

closest works better than parents because you can limit the search to the context of your menu.

Also, as an aside, you don't need to do a loop. You can just do this:

$("div#navigation").find("a[href='" + top.location.pathname + "']").addClass("active");

So your entire code should look like this:

$selected = $("div#navigation").find("a[href='" + top.location.pathname + "']");
$selected.addClass("active");
$selected.closest("li","#navigation").addClass("active");

Upvotes: 0

Related Questions