Right now my first year students are presenting the mockups for their sites in a class critique. A number of the designs have a navigation bar that highlights the current page. While it’s possible to add this feature by inserting an inline style into the appropriate link in the navigation bar of each page, doing so prevents it from being used as an include(), and ruins scalability.

Previously, I’ve shown how to achieve this effect with PHP and JQuery, but the most efficient method requires neither server-side technology nor frameworks.

The Markup

The HTML for this example could take practically any context; the important part is the identifier on the wrapping element. For this example, I’ll use a <nav>:

<nav id="main">
	<a href="/845/Self-Aware-Site-Navigation-With-JavaScript">This Page</a>
	<a href="/865/A-Complete-Web-Development-Reading-List-for-HTML>HTML</a>
	<a href="/919/A-Complete-Reading-List-For-CSS">CSS</a>
</nav>

The CSS

The presentation rules for the navigation bar are fairly straightforward:

@keyframes underline {
	to { border-bottom: 5px solid hsla(20,90%,50%, 1); }
}
#mainnav {
	text-align: center;
	margin: 2rem;
	font-size: 2rem;
}
#mainnav a {
	display: inline-block;
	text-transform: uppercase;
	margin: 1rem;
	text-decoration: none;
	color: inherit;
	letter-spacing: .1rem;
}

To this we’ll add a special class to indicate the current page. In this case, we’re calling on the animation:

a.current {
	animation: 2s underline forwards;
	font-weight: 900;
}

This class won’t be applied in our HTML, but in the DOM, via JavaScript, which is what we’ll look at next.

The JavaScript

In the script added to the end of the page we need to identify the current URL in the browser, strip everything out except the page name, and match the result against the links in the navigation bar: the href value that matches will be the current page. We’ll then apply the appropriate class to the corresponding link.

function cleanPath(path) {
	path = path.split("/").pop()
	path = path.split('#')[0];
	return path = path.split('?')[0]; 
}
	
var links = document.querySelectorAll("#mainnav a"),
currentURL = cleanPath(window.location.href);
	
for (var i=0; i < links.length; i++) {
	if (currentURL == cleanPath(links[i].href) ) {
		links[i].classList.add("current");
	}
}

The applied class brings in the animation for the current link in the navigation bar.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/rrWdmm