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:
  1. <nav>
  2.     <ul>
  3.         <li><a href="/">Home</a></li>
  4.         <li><a href="/about/">About</a></li>
  5.         <li><a href="/clients/">Clients</a></li>
  6.         <li><a href="/contact/">Contact Us</a></li>
  7.     </ul>
  8. </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:
  1. <script type="text/javascript">
  2.     $(function () {
  3.         var page = location.pathname.split("/")[1];
  4.         if (page != "") {
  5.             $('nav a[href^="/' + page + '"]').parent().addClass('active');
  6.         }
  7.     });
  8. </script>

JavaScript:
  1. <script type="text/javascript">
  2. (function() {
  3.     var nav = document.getElementById('nav'),
  4.         anchor = nav.getElementsByTagName('a'),
  5.         current = window.location.pathname.split('/')[1];
  6.         for (var i = 0; i < anchor.length; i++) {
  7.         if(anchor[i].href == current) {
  8.             anchor[i].className = "active";
  9.         }
  10.     }
  11. })();
  12. </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:
  1. = is equal
  2. != is not equal
  3. ^= starts with
  4. $= ends with
  5. *= contains

Reference: CSS-Tricks
Thursday 24 April 2014
Posted by Jebastin

Link To This Post/Page

Spread The Word

Add this button to your blog:
JJ Technology Solutions

Blog Archive

Trackers

eXTReMe Tracker
facebook

- Copyright © JJ Technology Solutions - Powered by Source Code Solutions -