I am using the code below to show/hide a navigation menu on click of an anchor.
The problem that I am having is that the first time the page loads, I have to click the anchor twice to get the menu to show. After that, I can toggle the menu with a single click. I can also click off the menu anywhere on the document to hide it.
Does anyone see a problem with the code below or know of a better way for me to hide the menu when a user clicks off the menu?
$('#aToggleQuickNavigation').click(function () {
$('#ulQuickNavigation').toggle();
});
$('html').click(function () {
if ($('#ulQuickNavigation').css('display') == 'block') {
$('#ulQuickNavigation').css('display', 'none');
}
$('#aToggleQuickNavigation').click(function (event) {
event.stopPropagation();
});
$('#ulQuickNavigation li a').click(function (event) {
event.stopPropagation();
});
});
Hide it if the click event bubbles all the way up to the body:
If the user clicks anywhere on the menu, you are already preventing the propagation of that click, so the body will never hear of it, and as such it will not be hidden.
Another thing I noticed is that you’re binding your click events within the click event handler of the HTML element. This can be pretty problematic. Each time a click bubbles up to the HTML element, you will be binding more and more click events.
Just stick with something like this for now: