I’ve got a set of menus that I would like to toggle on/off when a user clicks on an option bar (similar to the bar in Gmail which you move/label emails).
When a user clicks a button, the menu appears. When the user clicks another button, the previous menu disappears and the new one appears. This is working with the following code. However, what isn’t working is if the user clicks a button, then clicks the same button, the menu is not disappearing.
I understand why it’s not working, but not sure how to fix it. I think I need to add “if the open menu is the one you are clicking on, close it and dont open anything else.” But the if statements i’ve tried aren’t doing this.
$("#moving ul li").click(function() {
// If the button clicked has the "active" class (meaning the menu is already open)
if ($("#moving ul li.active") == this) {
// Close the menu (removing the visible class) and make the button no longer active
$(this).toggleClass("active")
$(this).children("ul").toggleClass("visible")
// Otherwise ...
} else {
// Find the open one and close it
$("#moving ul li.active").toggleClass("active")
$("#moving ul li ul.visible").toggleClass("visible")
// Open this menu
$(this).toggleClass("active")
$(this).children("ul").toggleClass("visible")
}
})
It’s not working because your if statement will never match.
“this” isn’t a jQuery object, it’s the actual DOM node. The statement should be: