Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Javascript display for active page in navigation.

Olivia Rhye

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])
{
$(this).addClass("navigationActive");
}
});
}

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.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy