demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my projects

CSSslidy: an auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

Self-Aware Site Navigation With jQuery

javascript / navigation

Estimated reading time: 2 minutes

Recently I demonstrated a simple “animated tabs” site navigation bar using CSS3. 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:

<script>
$(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');} 
		});
})
</script>

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). Obviously the example at the top of this article is simply there for show, as this blog lacks a products page.

comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.