Smashed Blog Development

Tag Archive: navigation

Mark active page with jQuery and CSS

Comments Off

This one is really handy. Sometimes you may need to change window.location.pathname, depending on how your URL structure works.

Assuming you have a menu set up in a list:

<ul id="nav">
	<li><a href="#">Link_1</a></li>
	<li><a href="#">Link_2</a></li>
	<li><a href="#">Link_3</a></li>
</ul>

Use the jQuery:

var url = window.location.pathname, 
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$('#nava').each(function(){
	if(urlRegExp.test(this.href.replace(/\/$/,''))){
		$(this).parents('li').addClass('active');
	}
});

And then some good old CSS:

#nav li.active a:hover {
	font-weight:700;
}