I have an “Options” button on my webpage. When the user click on that button, a little submenu appear.
When I click outside that menu, it closes. So far so good.
My problem is that when I click again on the option button(when the menu is visible), the menu stays open. It should close.
Here’s the code that manage the “click outside” functionality
$j(document).mouseup(function(e) {
var container = $j('.playlist-menu');
if (container.has(e.target).length === 0) {
container.hide();
}
});
And the event on the button
$j('#options').click(function() {
$j('.playlist-menu').toggle();
});
The HTML structure:
<button id="options" class="float-left" title="Options" type="button">
<div class="playlist-menu display-none">
<ul>
...
</ul>
</div>
I don’t understand why its not closing when I click a second time on the option button, the e.target of that button is not ‘playlist-menu’ so why is the menu not closing??
Thanks
It’s because when you click on the button, the menu is hidden by the event handler bound to the document, but, the event handler on the option button is fired as well. This triggers the menu to toggle it’s state making it visible.
To overcome this, check in the event handler bound to the document if the event target is not the options button as well as not an element from the menu.
So, something like this
Hope that makes sense.