jQuery: Main nav items selected depending on URL or page name

Posted by Ricardo on Stack Overflow See other posts from Stack Overflow or by Ricardo
Published on 2012-10-23T03:45:11Z Indexed on 2012/10/24 5:04 UTC
Read the original article Hit count: 231

Filed under:

Ok, I've looked all over for a solution for this but so far I'm unable to find anything related to what I need to accomplish.

What I need is very simple as far as logic goes.

I have a nav bar like this one:

<nav>
    <ul>
       <li><a href="download.shtml">Download</a></li>
       <li><a href="documentation.shtml">Documentation</a></li>
       <li><a href="contact.shtml">Contact</a></li>
       <li><a href="about.shtml">About</a></li>
    </ul>
</nav>

And the URLs of the site are straightforward:

http://domain.net/download.shtml
http://domain.net/documentation.shtml
http://domain.net/contact.shtml
http://domain.net/about.shtml

Question:

How can I detect which page/URL I'm on and add a class of .active to the corresponding nav item?

The end result would be, for example if I'm in the Download page:

<nav>
    <ul>
       <li><a href="download.shtml" class="active">Download</a></li>
       <li><a href="documentation.shtml">Documentation</a></li>
       <li><a href="contact.shtml">Contact</a></li>
       <li><a href="about.shtml">About</a></li>
    </ul>
</nav>

Thanks in advance for any help on this matter.

© Stack Overflow or respective owner

Related posts about jQuery