Recently I demonstrated a simple “animated tabs” site navigation bar using CSS. While the styles work well, there was an issue with the tab that represented the current, active page. In the code I provided it was necessary to apply a particular style for the current page tab to the matching link in the markup. This is fine in principle, but the approach means that when we make a new page, we cannot simply copy and paste the navigation bar code; we must alter the application of a style to the tab that represents the current page. This also means that we cannot use the navigation as part of a server-side include.

While you can get around this issue by using PHP, it comes at the cost of somewhat complex code and a small server-side hit to performance.

If you could guarantee that the majority of visitors had JavaScript enabled on their browsers, you could use a client-side solution instead; here, I’ll use jQuery to keep the code concise.

After ensuring that JQuery is loaded and that your navigation is marked up in a matching fashion (as written, the script will look for an unordered list with a role of navigation, and add an id style of forefront to the matching link within it) add the following at the top of a page:

$(document).ready(function(){
	var url = (window.location.href.split('#')[0]);
	url = (url.split('?')[0]);
	$('ul[role="navigation"] a').each(function() {
		var target = (this.href.split('#')[0]);
		target = (target.split('?')[0]);
		if (target === url) {
			$(this). attr('id', 'forefront');
		} 
	});
})

Typically, you would externalize this script and link to it inside a <script> tag, as it would be used on every page.

This script adapts to many circumstances: a GET URL (with a ? in the link) and/or anchor link (a # in the link).