I am using the following jQuery to change classes on elements in an unordered list. It doesn't seem like it is the most effective way of achieving the effect. Is there a better way to write this?
$(function() {
$('nav li a').click( function() {
$(this).parent().siblings().children().removeClass('active');
$(this).addClass('active');
});
});
Thanks
S
It's usually simpler in these cases to attach the handler to the <li>
and let the click bubble up from the <a>
(which happens by default). Then your handler looks like this:
$(function() {
$('nav li').click( function() {
$(this).addClass('active').siblings().removeClass('active');
});
});
Then in your CSS you just account for active
being on the <li>
, like this:
li.active a { color: red; }
As an aside, if you have many <li>
elements you'll want to use .delegate()
like this:
$('nav').delegate('li', 'click', function() {
$(this).addClass('active').siblings().removeClass('active');
});
Also note that if you want to remove 'active'
from all elements except this
then you could get away with something as simple as
$('.active').removeClass('active');
$(this).addClass('active');
And that should propagate through the tree pretty easily. However, I can see it causing a headache on performance if the DOM is heavily populated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With