Javascript display for active page in navigation.

December 17, 2012

I’ve noticed a few people saying that they want a javascript file to add a class for displaying active pages in navigation. I figured we’d make one and just throw it out there.

This is going to be in jQuery.

First we want to to make an unordered list (UL) filled with our navigation links. Define the navigation with “nav”. (I know, original, right?)

Now make your li’s with a links inside. Make sure that all pages can be linkable by these nav’s.

Now comes the easy part.

function findActive()
	var thisPage = window.location.pathname;
	var thisFile =  thisPage.split("/");
	var pageInteger = thisFile.length -1;
	jQuery.each($("#nav li a"), function(){
		var thisLink = $(this).attr("href");
		var thisLinkFile = thisLink.split("/");
		var thisLinkInteger = thisLinkFile.length -1;
		if(thisFile[pageInteger] ==thisLinkFile[thisLinkInteger])

What this is doing is simply grabbing the last bit of the navigation links and comparing it to the window url path in order to find a match. You might recognize the methodology from the breadcrumbs script.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive