1

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?

6
  • Didn't you already answer #2 yourself? Commented Dec 17, 2012 at 22:15
  • Users should not have to click to close - they should be able to simply mouse-out of the menu. Commented Dec 17, 2012 at 22:16
  • 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. Commented Dec 17, 2012 at 22:18
  • 1
    @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. Commented Dec 17, 2012 at 22:19
  • @j08691 Yes I did, but my question is if it's the recommended pattern or if the way I did it is inefficient. Commented Dec 17, 2012 at 22:19

1 Answer 1

3

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

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

jsFiddle example

Sign up to request clarification or add additional context in comments.

2 Comments

Meeehhhh not as elegant as mine :-P
This does what I want. I suppose I was already 90% there since I was doing the same for the rest of the document, but for some reason did not apply the same thought process for the submenu :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.