With the help of this post I was able to put together a menu that closes either by toggling a link or clicking outside of it (via mouseup). The problem is that because this mouseup event handler is bound to the document object this is constantly being fired regardless of whether the menu is open or not.
I was wondering how could I conditionally set this handler up only when the menu is visible? I don't necessarily want to invoke: $(document).off("mouseup");
outright in that this toggle is ever fired to initiate the event listener inside $toggleMenu.on("click", function() {...})
via $(document).on("mouseup")
$(function() {
var $toggleMenu = $(".toggle-menu"),
$menu = $(".menu");
$toggleMenu.on("click", function(e) {
e.preventDefault();
toggleUserMenu();
});
$toggleMenu.on("mouseup", function(e) {
e.stopPropagation();
});
$(document).on("mouseup", function (e) {
console.log("Event is still firing");
if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
$menu.hide();
}
});
function toggleUserMenu() {
var menuIsVisible = $menu.is(":visible");
if (menuIsVisible) {
$menu.hide();
} else {
$menu.show();
}
}
});
.toggle-menu {
color: #444;
display: inline-block;
margin-bottom: 15px;
text-decoration: none;
}
.menu {
border: 1px solid black;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="" class="toggle-menu">Toggle Menu</a>
<div class="menu">
<a href="#" class="menu-item">Menu Item 1</a>
<a href="#" class="menu-item">Menu Item 2</a>
<a href="#" class="menu-item">Menu Item 3</a>
</div>