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 usingthis
as a parameter:You can use
removeClass()
/addClass()
method like below snippet.