Active jQuery menu

I am trying to create a jquery menu 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? Thank:)

+3
source share
3 answers

The source code failed because this syntax is invalid:

.children().("a")

The rest of the code also had some fundamental flaws. Try instead:

$(function () {
  $('.buttons a').click(function (event) {
    var $target = $(event.target);
    var $li = $target.parent();
    $li.addClass('selected').siblings().removeClass('selected');
  });
});

In this amendment, the class selectedis applied to <li>-not a <a>- to provide more flexibility when writing CSS.

+5

:

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

to

$("this").addClass('selected').siblings().removeClass("selected");
+2
$(document).ready(function() {
  $(".buttons a").click(function() {
    $(".buttons a").removeClass("selected");
    $(this).addClass("selected"); 
  });
});
+1

Source: https://habr.com/ru/post/1738605/


All Articles