Auto Detecting Nav Hilighter with jQuery

More jQuery love is going down… it seems to be the theme of the month.

This last weekend I picked up the ‘jQuery in Action’ book and it really opened my eyes to just how cool jQuery is. I mean, I was pretty stoked about it already, but now I want to take it out to dinner and maybe make out with it a little in the back of my car.

So, reading the book, I learned just how powerful their wrapper element is. A lot of it’s css-based, so it’s easy for a front-end dev type like myself to catch up on, and then it mixes in simple regular expressions and has() checks and .. my mind is blown.

I wrote this little function last night to both test some advanced wrapper selectors and solve a practical and common goal: hilighting the navigational item of the active page. Before, we’ve done all types of things to accomplish this goal, mostly dealing with writing some sort of server-side code that detects the page and does an if statement to add a class to the markup.

It would always get kind of messy.

But no more! Here’s the function that turns that former headache into a simple JS function call:

function activateNav(nav) {
// split url and get page (or lack of page - index)
var url = document.location.href;
var urlSplit = new Array();
urlSplit = url.split('/');
var page = urlSplit[urlSplit.length-1];

// catch for root (index)
if(page == ”) {
page = ‘index’;
}

// detect location of nav items and classify right one
$(nav+’ a[href*='+page+']‘).parent().addClass(’active’);
}

Breaking it down into detail, the code above gets the page from the url (the string split on the ‘/’ character and pulling the last array item provides a consistent way of getting only the page file name) and then checks all of the nav link href attributes to see where they’re linking to. If the page name matches any part of the link target, the javascript will add an active class to the element containing the link.

Natrually, this is set up for a list-type nav. Adding the active class to the parent tag and not the anchor itself may or may not be the smartest thing to do, but it made the most sense to me at the time (since 99% of my navs are in lists).

As this code evolves I’m sure it’ll change, but that’s part of the beauty of jQuery - it feels so natural to scale.

0 Responses to “Auto Detecting Nav Hilighter with jQuery”


  1. No Comments

Leave a Reply