Archive for April 2014
How to 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:
HTML:
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.
jQuery:
JavaScript:
Essentially that will match links in the nav who's href attribute begins with "/about" (or whatever the secondary directory happens to be).
Comparison Operators:
Reference: CSS-Tricks
Let's say you have navigation like this:
HTML:
- <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.
jQuery:
- <script type="text/javascript">
- $(function () {
- var page = location.pathname.split("/")[1];
- if (page != "") {
- $('nav a[href^="/' + page + '"]').parent().addClass('active');
- }
- });
- </script>
JavaScript:
- <script type="text/javascript">
- (function() {
- var nav = document.getElementById('nav'),
- anchor = nav.getElementsByTagName('a'),
- current = window.location.pathname.split('/')[1];
- for (var i = 0; i < anchor.length; i++) {
- if(anchor[i].href == current) {
- anchor[i].className = "active";
- }
- }
- })();
- </script>
Essentially that will match links in the nav who's href attribute begins with "/about" (or whatever the secondary directory happens to be).
Comparison Operators:
- = is equal
- != is not equal
- ^= starts with
- $= ends with
- *= contains
Reference: CSS-Tricks