Bootstrap twitter Active Navigation Bar - changing class names using JQuery
css, html, jquery, twitter-bootstrap
Solution
To answer your question in the comment to the first answer, .parents('li') would get any li parents found as you walk up the DOM from your current position. Adding the :first pseudo-selector ensures you get the first one found.
A better solution is to use .parent (singular.) Such as: `$thisLi.parent('ul')`. I don't belive that is your problem though...
Is it possible the browser is just loading a new page on you? I don't see you calling `event.preventDefault()`, in fact you don't capture the event in your code, you just respond to it...
Also, .on is the preferred way to bind to events now:
$(function(){
$('.nav li a').on('click', function(e){
e.preventDefault(); // prevent link click if necessary?
var $thisLi = $(this).parent('li');
var $ul = $thisLi.parent('ul');
if (!$thisLi.hasClass('active'))
{
$ul.find('li.active').removeClass('active');
$thisLi.addClass('active');
}
})
})
Problem
Im using bootstrap twitter and I would like my different sites in the menu to show as active when clicked on. I've found the question Bootstrap Twitter CSS Active Navigation which deals with this issue. My problem is that i cannot make the JQuery function in one of the answers to work. The modifications should be very straight forward to make it work in my case which in HTML is: ``` <script> $('body').on('.nav li a', 'click', function() { var $thisLi = $(this).parents('li:first'); var $ul = $thisLi.parents('ul:first'); if (!$thisLi.hasClass('active')) { $ul.find('li.active').removeClass('active'); $thisLi.addClass('active'); } }); </script> <ul class="nav nav-pills pull-left"> <li class="active"> <a href="home.html">Home</a> </li> <li> <a href="about.html">About</a> </li> </ul> ``` Any clues as to what might be the problem? Thank you in advance.