On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the
Looking at some of the other answers, if you want the webpage to scroll down to that section when a side menu is clicked then you don't want to preventDefault
.
Additionally, you only need to remove the current active class and add a new one not search through all li's. You also want the code to not do anything when the list item you've selected is already active—not needlessly add and remove the same active class. Lastly you should put your event listener on the a element not the li as it has an easier time of triggering a click event on iPhones and tablets, etc. Could also use .delegate
so you don't have to wait for a DOM ready event. So in the end I'd do something like this (I assume you've preloaded jQuery):
$('body').delegate('.menu 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');
}
});