jQuery add class .active on menu


HTML

<div class="menu">

<ul>
<li><a href="~/link1/">LINK 1</a>
<li><a href="~/link2/">LINK 2</a>
<li><a href="~/link3/">LINK 3</a>
</ul>

</div>

CSS:

.active { color: #fff; background: #ef7f00; }

JS:

<script type="text/javascript">

jQuery(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
jQuery('.menu a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
jQuery(this).addClass('active');
}
});

});

</script>

Advertisements

6 thoughts on “jQuery add class .active on menu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s