Baseball Vault
Baseball Vault

Reputation: 33

How can I close a dropdown menu with a click anywhere else on the page and remove the class "selected"?

Here is the jquery code I am using to show and hide my menus.

jQuery(window).load(function () {
    $("#nav > li > a").click(function () { // binding onclick
        if ($(this).parent().hasClass('selected')) {
            $("#nav .selected div div").hide(); // hiding popups
            $("#nav .selected").removeClass("selected");
        } else {
            $("#nav .selected div div").hide(); // hiding popups
            $("#nav .selected").removeClass("selected");
            if ($(this).next(".subs").length) {
                $(this).parent().addClass("selected"); // display popup
                $(this).next(".subs").find("*").slideDown(200);
            }
        }
    });
});

Currently, to hide the drop downs the viewer must click back on the menu heading. I would like to add the function where if they click anywhere else on the page then the menu will hide.

I have read the usual answers but am having trouble integrating them AND properly removing the "selected" class.

I've put everything in jsFiddle here, but unfortunately the code doesn't work on jsFiddle (menus don't drop down). It does, however, work on my live pages when I upload them. Anyone answers as to why that might be would also be helpful and probably get a final solution faster.

Upvotes: 3

Views: 4414

Answers (1)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

This should have all you need: http://jsfiddle.net/PysAY/5/

Other than getting the fiddle to work, I made very few changes.

First, I made a new function, encapsulating what you were doing when the selected menu was clicked. Since you want the same functionality to occur when clicking off the menu at all, it should be its own function.

var closeMenu = function() {
    $("#nav .selected div div").hide(); // hiding popups
    $("#nav .selected").removeClass("selected");
};

Then I changed your menu's click handler to call that function:

$("#nav > li > a").click(function (e) { // binding onclick
    if ($(this).parent().hasClass('selected')) {
        closeMenu();
    } else {
        // ...
        e.stopPropagation()

I added lines at the top and bottom of your click handler to stop the event propagation. That way, the body click event below won't receive a click that opens the menu and immediately close it.

Finally, I added a click handler to the body:

$("body").click(function () {
    closeMenu();
});

It simply calls the closeMenu function any time a click is received. As mentioned above, we do a stopPropagation on other click events to make sure that this only happens when nothing else does. (In the fiddle, your entire body is the menu bar, so you'd have to click somewhere on the bar that will not cause the dropdown to occur. This will work better on your test platform.)

Upvotes: 1

Related Questions