tags:

views:

70

answers:

2

Hi All I'm looking for a simple unobtrusive way to add a class="active" to an unordered list menu based on the directory it's in. Unfortunately I can't add a custom class to the body tag so I'm unable to use a pure css solution.

Can anyone point me to a good tutorial - I've looked but can't find one that fit's my needs. Code looks like this, I just need to add the class based on /directory/ or / a jquery solution would be ideal as I'm already loading the jQuery library.

<ul class="nav">
<li><a href="/index.html">Home</a></li>
<li><a href="/about/about.html">About Us</a></li>
<li><a href="/cv/submit-your-cv.html">Submit CV</a></li>
<li><a href="/vacancies/index.html">Vacancies</a></li>
<li><a href="/news/news.html">Company News</a></li>
<li><a href="/praise/praise.html">Praise</a></li>
<li class="nosep"><a href="/contact/contact.html">Contact Us</a></li>
</ul>
A: 

You could look at the window.location variable and set an id to each li-element. Then something like:

$("...").addClass("myCssClass");

Hope it helps in some way...

dale
+6  A: 

Try this:

$(".nav li:has(a[href$='"+window.location.pathname+"'])").addClass("active");
Nick Craver
Hi Nick, this is great but it seems to fail for the index page? Any thoughts on making that work?
toomanyairmiles
the problem seems to be that the active class doesn't appear when the user accesses / rather than /index.html in addition if any other page is called index.html the script duplicates the active class.
toomanyairmiles
@toomanyairmiles - Is making the URLs absolute an option, or do you know what the full path will be?
Nick Craver
@Nick, I can put absolute urls in some of the menus, but some of the sections are blogs and they need to inherit the class from their root directory.
toomanyairmiles
@toomanyairmiles - If your site is at the root, then you can just take out `$=` and replace with `=`, changing from "ends with" to a plan equals, see if that does what you want...without knowing your layout I can't say exactly.
Nick Craver