I am trying to set the class of the ‘li’ tag to ‘active’ whenever the user click on any link place inside ‘li’ tag.
Code snippet of navbar of bootstrap is show below:
<div>
<div>
<a href=”#”>Title</a>
<ul>
<li><a href=”Home.aspx”>Home</a></li>
<li><a href=”Page1.aspx”>Page1</a></li>
<li><a href=”About.aspx”>About Us</a></li>
</ul>
</div>
</div>
Now when user click on ‘Page1′, class of li associated with it is set to ‘active’.
jQuery to obtaing that behaviour is shown below:
<script type=”text/javascript”>
$(document).ready(function () {
var url = window.location;
// Will only work if string in href matches with location
$(‘ul.nav a[href=”‘ + url + ‘”]’).parent().addClass(‘active’);// Will also work for relative and absolute hrefs
$(‘ul.nav a’).filter(function () {
return this.href == url;
}).parent().addClass(‘active’);
});
</script>
References:
1. http://twitter.github.com/bootstrap/components.html#navbar
2. http://stackoverflow.com/questions/11533542/twitter-bootstrap-add-active-class-to-li






Leave a Reply