No need to bind a click event to each ID but instead bind to all of the list items of this unordered list. Then use the .parent().children() methods. Following should work:
$('ul li').click(function(){
$(this).addClass('active');
$(this).parent().children('li').not(this).removeClass('active');
});
You'll probably find this better (otherwise the page will jump) -
$(function() {
$("li").click(function() {
// remove classes from all
$("li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
// stop the page from jumping to the top
return false;
});
});
You can add active class using below single line without using any event
$('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
link to refer
You can do:
$('li').click(function(e){
e.preventDefault();
$(this).addClass('active');
$(this).siblings().each(function(){
$(this).removeClass('active') ;
});
});
fiddle here http://jsfiddle.net/UVyKe/1/
Give the ul an id or class, and select off of it.
<ul id = "nav">...
var $navItems = $('#nav > li');
$navItems.click(function(){
$navItems.removeClass('active');
$(this).addClass('active');
});
$(function() {
$("li").click(function() {
// remove classes from all
$("li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
});
It would be wise to give meaningful classes to the <li>
's so you can properly select just those, but you get the idea.