Activeclasshref

by narensrinivasans

HTML

<ul id="myTab">
    <li><a href="http://jsfiddle.net/narensrinivasans/6xhTs/5/">Test</a></li>
    <li><a href="http://jsfiddle.net/narensrinivasans/6xhTs/4/">Test</a></li>
    <li><a href="http://jsfiddle.net/narensrinivasans/6xhTs/6/">Test</a></li>
</ul>

CSS

li { float:left; margin-right:12px; list-style:none; }
li.active { background: #0d0; }
a { color:#000; }

JavaScript

$(function(){

    var url = window.location.pathname, 
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
        // now grab every link from the navigation
        $('#myTab li a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
				$('#myTab li.active').removeClass('active');
                $(this).parent('li').addClass('active');
            }
        });

});