I have some dynamically created menus on a page that need to hide whenever the user clicks anywhere on the page. This needs to work if the user clicks the menu, or tries to open another menu.
I also want the event handler to unbind itself when done hiding. I've found a solution using document.on()
one one()
but would really like to restrict the document
handler to something further down the DOM. Problem is that it breaks my code.
Any help with an elegant solution appreciated.
The main reason I want to do this is to be able to prevent event propagation
such as in:
Succeeding propagation, failing one()
clickhandler DEMO
Javascript
// I want to change "document" to ".menus" here
$(document).on("click", ".displayMenu", function(e)
{
var $menu = $(this).siblings(".menu");
$(document).one("click", function(e2)
{
if (e.target!=e2.target)
$menu.hide();
});
$menu.toggle();
});
HTML
<div class="menus">
<div>
<div class="displayMenu">Show menu 1</div>
<div class="menu">menu 1</div>
</div>
<div>
<div class="displayMenu">Show menu 2</div>
<div class="menu">menu 2</div>
</div>
</div>