jQuery.navActives - Navigation Highlighting
jQuery October 26th, 2008Nav highlighting can be a little tricky. It usually gets tricky when there is more than one level of secondary nav.
How do we know to hide or show sublinks, and how do we know when to highlight an associated “Overview” link? Or, what if your page is not in the left nav links, but you still want to highlight its parent? The list of caveats grows as you try to answer those questions, so I set out to make something that applies to these squirrely situations, instead of having to write a custom function each time.
jQuery.navActives scans through a specified list of links and finds the clostest matches to a given url (generally the current address - window.location.href).
Usage
j("#yourlinkcontainer a").navActive(options, callback(this, activeLinks, highestMatch));
The call back function is passed 3 parameters. The jQuery object calling the callback (this), an array of the matching links (activeLinks), and the highest match rigidity found (highestMatch).
Like my other plugins, we need to pass it some settings. Here’s an example of what I use for some primary navigation:
var mainNavHighlight = {
matchUrl:currentPageUrl,
alterElements: [{element:"each", className:"active"}],
rigidity:[1]
};
j(”div#siteHeader a”).navActives(mainNavHighlight);
Notice the rigidity. That is basically the number of items past the main URL to compare. That is one reason I have the Home Page in a “/home/” directory.
It is important that you organize ALL sections and sub sections in their own folder. Here’s a complex example of a navigation list that has parent and sub lists:
var sideNavHighlight = {
matchUrl:currentPageUrl,
alterElements: [{element:"each", className:"current"},
{element:"each.parents('ul:first').parent().children('a')", className:"current"},
{element:"each.siblings('ul:first').find('a:first')", className:"current"}],
rigidity:[1,2,3]
};
j(”div#sideNav a”).navActives(sideNavHighlight, showActiveSubs);
function showActiveSubs(i, list, high){
jQuery.map(list, function(n){
if(n.rigidity>=2){
jQuery(n.link).parents(”ul”).css(”display”,”block”);
}
});
}
Notice the alterElements setting, the rigidity, and the showActiveSubs function that uses the list of matched URLs returned by navActives.
February 26th, 2009 at 3:39 am
Hi Stephen,
I’d really like to use your script, but the link to the file’s broken.
February 26th, 2009 at 1:35 pm
Thanks for bringing this to my attention. The link should be working now. Let me know if you have any questions!