jQuery menu active link

14,730

Solution 1

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.

Solution 2

I would change:

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

to

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

Solution 3

$(document).ready(function() {
  $(".buttons a").click(function() {
    $(".buttons a").removeClass("selected");
    $(this).addClass("selected"); 
  });
});
Share:
14,730
b0nd
Author by

b0nd

Updated on June 04, 2022

Comments

  • b0nd
    b0nd almost 2 years

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

  • jps
    jps about 14 years
    The only problem is that this may produce erratic results due to race conditions where you can't be sure addClass will be fired after RemoveClass.
  • user3167101
    user3167101 about 14 years
    @Jud You are correct, however I have used this in production code and never had it clash with itself.
  • user3167101
    user3167101 about 14 years
    Forgive me if I am wrong, but doesn't JavaScript's single threaded nature mean that it will run each line one at a time, invoking any extra code (like jQuery's internal methods) before moving onto the next line to execute?
  • jps
    jps about 14 years
    I wouldn't bet too much on it, but I implemented that exact function with varying results. But, if it works in this scenario, why fix it?
  • b0nd
    b0nd about 14 years
    your solution works, but unfortunately it doesn't give the flexibility to style the parent tag. Thanks