jQuery - toggle click two times

Viewed 73

This is my code (toggle menu):

$(function () {
    $('#menu li').click(function () {
        $('#menu li').removeClass("active");
        $(this).toggleClass("active");
    });
})      

Works perfectly. But... If I click on one element and click on it again, the toggle does not close. I would like the menu to close after the second click.

$(function () {
    $('#menu li').click(function () {
        $(this).toggleClass("active");
    });
})      

If I do so, the menu closes after the second click, but... I can expand other menus and the previous one does not close.

How to combine both of these functionalities?

2 Answers

When removing the class from all other li element, simply exclude the one you just clicked on with chaining the .not() function using this as a parameter:

$(function () {
    $('#menu li').click(function () {
        $('#menu li').not(this).removeClass("active");
        $(this).toggleClass("active");
    });
})    
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

You can use removeClass()/addClass() method like below snippet.

$(function () {
    $('#menu li').click(function () {
        $('#menu li').removeClass("active");
        $(this).addClass("active");
    });
})    
li{
  background: #dddddd;
  margin: 6px 0;
  padding: 8px 10px;
  cursor: pointer;
}
.active {
  background: #00ff00;
  color: #0000ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="menu">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Related