Add Active Navigation Class Based on URL
Ideally you output this class from the server side, but if you can't...
Let's say you have navigation like this:
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/clients/">Clients</a></li>
<li><a href="/contact/">Contact Us</a></li>
</ul>
</nav>
And you are at the URL:
http://yoursite.com/about/team/
And you want the About link to get a class of "active" so you can visually indicate it's the active navigation.
$(function() {
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
Essentially that will match links in the nav who's href attribute begins with "/about" (or whatever the secondary directory happens to be).
I’ve been struggling trying to get something like this to work on a templated HTML website (server side CSS updating not available). The structure of the menu is a little more complex than your example. Would your CSS trick work for this structure? If so, PLEASE enlighten me because I’m stuck.
Pure Javascript:
Thanks for every things
Danke Chris! Simple, clear and slick. High five!
Thanks! Been looking for something like this for a while now :)
Works like a charm with one exception. One the home page the class is added to all the links. The all start with /. Any help would be appreciated.
Indeed. As well that pages that are called for example /about en /aboutsome are also both ‘active’ when you press ‘about’. Any solution for this, like a sort of exact matching?