Twitter Bootstrap add active class to li
For Bootstrap 3:
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');
Update
For Bootstrap 4:
var url = window.location;
// Will only work if string in href matches with location
$('ul.navbar-nav a[href="'+ url +'"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.navbar-nav a').filter(function() {
return this.href == url;
}).parent().addClass('active');
We managed to fix in the end:
/*menu handler*/
$(function(){
function stripTrailingSlash(str) {
if(str.substr(-1) == '/') {
return str.substr(0, str.length - 1);
}
return str;
}
var url = window.location.pathname;
var activePage = stripTrailingSlash(url);
$('.nav li a').each(function(){
var currentPage = stripTrailingSlash($(this).attr('href'));
if (activePage == currentPage) {
$(this).parent().addClass('active');
}
});
});
You don't really need any JavaScript with Bootstrap:
<ul class="nav">
<li><a data-target="#" data-toggle="pill" href="#accounts">Accounts</a></li>
<li><a data-target="#" data-toggle="pill" href="#users">Users</a></li>
</ul>
To do more tasks after the menu item is selected you need JS as explained by other posts here.
Hope this helps.
if you put
data-toggle="pill"
in the tag it should work automatically.
http://twitter.github.com/bootstrap/javascript.html#tabs
read under Markup