1
votes

I created a "dropdown menu" in HTML that appears when you click on an element. If you click on the element it will apply a class "selected" to the li which will cause the submenu to appear:

jsFiddle Example

I have code to right now that will show/hide the menu when clicking on the menu item. If a different menu is selected it will remove the selected class from it and toggle it on the one that was clicked:

$("#menu").on("click", "li.dropdown", function(event) {
    event.preventDefault();
    event.stopPropagation();

    $(this).siblings(".dropdown").removeClass("selected");
    $(this).toggleClass("selected");
});

The problem is that the way I have this right now when I click on a child within the submenu it will toggle the menu and close it.

I also want to hide the menu when clicking anywhere else in the document. This can be accomplished via:

$(document).on("click", function(event) {
    $("#menu .dropdown").removeClass("selected");
});

1) How do I enable this toggle functionality without hiding the menu when the dropdown portion is clicked?

2) How do I hide the menu when clicking anywhere else on the document other than the menu / submenu itself?

1
Didn't you already answer #2 yourself? - j08691
Users should not have to click to close - they should be able to simply mouse-out of the menu. - Diodeus - James MacFarlane
Although, @Diodeus, it can be good to use a short timeout before auto-closing the menu - if you have several sub-menus it's really annoying when you accidentally mouse off the edge and the whole thing closes immediately. - nnnnnn
@Diodeus No. It's perfectly acceptable to have it stay up when not hovering. Especially considering a tablet that doesn't have the concept of hovering. - Dismissile
@j08691 Yes I did, but my question is if it's the recommended pattern or if the way I did it is inefficient. - Dismissile

1 Answers

3
votes

You seem to have answer #2 in an acceptable manner. To do #1:

$('.submenu').click(function(e) {
    e.stopPropagation();
});​

jsFiddle example