Posted By

vaughanj on 04/06/13


Tagged

url navigation active


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

imoddesign


Adding an active class to nav links based on URL with jQuery Address


 / Published in: jQuery
 

URL: http://davemcmillan.net/424/snippets/adding-an-active-class-to-nav-based-on-url-with-jquery-address/

What this does is it adds the attribute “data-path” to each of the nav links, and gives this attribute a value of whatever comes after the “base” URL. Because we are using jQuery Address, we have the (event.value) variable to play with. This value is automatically set to be whatever is after the “base” value too, which means we can now check to see if these values equal each other. If they do, the active class is added to the link. Remember, this function resides inside the jQuery.address.change function, so it will be run every time a new link is clicked.

  1. <nav>
  2. <ul>
  3. <li><a href="http://yourdomain.com/about.html">About</a></li>
  4. <li><a href="http://yourdomain.com/services.html">Services</a></li>
  5. <li><a href="http://yourdomain.com/contact.html">Contact</a></li>
  6. </ul>
  7. </nav>
  8.  
  9. <!-- 1. Assign the domain /home page” URL to a variable -->
  10.  
  11. var base = 'http://yourdomain.com';
  12.  
  13. <!- 2. Loop through the nav links, add a value for data-path, and add ‘active’ class -->
  14.  
  15. jQuery.address.change(function(event) {
  16.  
  17. if (event.value) {
  18.  
  19. // remove active class on all nav links
  20. $("nav ul li a").removeClass("active");
  21.  
  22. // get current link and add active class to it
  23. $("nav ul li a").each(function() {
  24. var dataPath = jQuery(this).attr("href").replace(base, '');
  25. $(this).attr("data-path", dataPath);
  26. if (dataPath == (event.value)) {
  27. $(this).addClass("active");
  28. }
  29. });
  30.  
  31. }
  32.  
  33. });

Report this snippet  

You need to login to post a comment.