I have a list of links, and I would like to use jQuery to set the clicked one as active, and have the rest of them remove their class.
My current setup is like this:
html
<ul>
<li id="li_1" class="active"><a href="#" id="link1">link 1</a></li>
<li id="li_2"><a href="#" id="link2">link 2</a></li>
<li id="li_3"><a href="#" id="link3">link 3</a></li>
</ul>
jquery
$("#link1").click(function () {
$("#li_1").removeClass('active');
$("#li_2").removeClass('active');
$("#li_3").addClass('active');
});
$("#link2").click(function () {
$("#li_1").addClass('active');
$("#li_2").removeClass('active');
$("#li_3").removeClass('active');
});
$("#link3").click(function () {
$("#li_1").removeClass('active');
$("#li_2").addClass('active');
$("#li_3").removeClass('active');
});
Obviously this isn't pretty in the least, and I'd like to have it become an extremely simple and flexible 1-2 liner function. I know this is possible, but unfortunately I don't possess the jQuery-fu that I know many of you do :)
$('ul > li > a').click(function() {
$(this).parent().addClass('active').siblings().removeClass('active');
return false;
});
Or perhaps better would be to place an ID on the <ul>
:
$('#myUL > li > a').click(function() {
$(this).parent().addClass('active').siblings().removeClass('active');
return false;
});
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