Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery “active” class assignment for the parent

Tags:

jquery

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!

like image 787
eran Avatar asked Jun 05 '26 18:06

eran


1 Answers

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

like image 141
Gabriele Petrioli Avatar answered Jun 08 '26 00:06

Gabriele Petrioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!