jQuery menu active link

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 :)

Answers


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.


I would change:

$(".buttons").children().toggleClass("selected").siblings().removeClass("selected");

to

$("this").addClass('selected').siblings().removeClass("selected");

$(document).ready(function() {
  $(".buttons a").click(function() {
    $(".buttons a").removeClass("selected");
    $(this).addClass("selected"); 
  });
});

Need Your Help

How to access an enum through an array object instance of a class

c# arrays class oop enums

I'm wondering if it's possible for me to access an enum that is declared within a class through an array object of the class...so far, I'm unable to access it. Here is an illustration.

Recurring Appointments in Dynamics CRM

javascript dynamics-crm

It doesn't look like Dynamics allows for recurring appointments. I found a tutorial for recurring service activities, but I don't really follow the portion where it sends a SOAP object. If anyone can