Reputation: 119
I am trying to make a jquery menu that when I click on one of the links (without reloading the page), it changes its class to "active" and removes this class when I click on another link.
here is my code :
<script type="text/javascript">
$(document).ready(function() {
$(".buttons").children().("a").click(function() {
$(".buttons").children().toggleClass("selected").siblings().removeClass("selected");
});
});
</script>
<ul class="buttons">
<li><a class="button" href="#">Link1</a></li>
<li><a class="button" href="#">Link2</a></li>
<li><a class="button" href="#">Link3</a></li>
<li><a class="button" href="#">Link4</a></li>
</ul>
Can someone tell me why my code is not working and how to fix it? Thanks :)
Upvotes: 3
Views: 14796
Reputation: 14644
The original code failed because this syntax is invalid:
.children().("a")
The rest of the code also had some fundamental flaws. Try this instead:
$(function () {
$('.buttons a').click(function (event) {
var $target = $(event.target);
var $li = $target.parent();
$li.addClass('selected').siblings().removeClass('selected');
});
});
In this correction, the class selected
is applied to an <li>
—not an <a>
—to give you better flexibility while writing CSS.
Upvotes: 5
Reputation: 11597
I would change:
$(".buttons").children().toggleClass("selected").siblings().removeClass("selected");
to
$("this").addClass('selected').siblings().removeClass("selected");
Upvotes: 2
Reputation: 490143
$(document).ready(function() {
$(".buttons a").click(function() {
$(".buttons a").removeClass("selected");
$(this).addClass("selected");
});
});
Upvotes: 1