user1375823
user1375823

Reputation: 105

jQuery dropdown menu not closing

I made a dropdown menu, the first item menu you click on for the sub-menu to appear and any sub-menus within that show/hide on hover/hover off. The only problem I'm having is I want the main navigation to close on clicking anywhere on the document.

jQuery(document).ready(function () {
        jQuery(".mainNav ul li").click(function () {
            jQuery(this).find("> ul").css({ "opacity": "1", "visibility": "visible", "top": "30px" });
            });
        jQuery(".sub-menu li").mouseover(function () {
            jQuery(this).find("> ul").css({ "opacity": "1", "visibility": "visible", "top": "30px" });
        });
        jQuery('.sub-menu li').mouseout(function () {
            jQuery(this).find("> ul").css({ "opacity": "0", "visibility": "hidden", "top": "35px"});
        });});

//the code i tried below
jQuery('document').click(function () {
        jQuery(.mainNav ul li ).find("> ul").css({ "opacity": "0", "visibility": "hidden", "top": "35px"});
    });});

    }); 

I assume the two click events are conflicting, but I'm not too sure familiar with how to handle it.

I messed around and the drop down closes if for example I change the click event onto a 'h1' element, which is right below it. I then changed it to .container and the sub menu doesn't even come up at all.

Upvotes: 0

Views: 146

Answers (2)

Zach Saucier
Zach Saucier

Reputation: 25944

You can use jQuery's .not or :not

jQuery(document).not(".mainNav ul").click(function () {
    jQuery(".mainNav ul li").find("> ul").css({ "opacity": "0", "visibility": "hidden", "top": "35px"});
});});

You're missing some parenthesis in the selector which I added as well

You also have an extra set of }); and your document click function is not inside of the ready function. Try putting it inside of the ready function, like so by removing the }); after the mouseout

On a side note you can use $ instead of jQuery if you'd like

Edit

I got it to work in my jsFiddle using :not and on("click",... Try the the full jQuery if just this snippet doesn't work

jQuery(document).on("click", ":not(.mainNav ul, .mainNav ul *)", function () {
    jQuery(".mainNav ul li").find("> ul").css({
        "opacity": "0",
            "visibility": "hidden",
            "top": "35px"
    });
});

Upvotes: 1

Jai
Jai

Reputation: 74738

you can try this:

jQuery(document).not('.mainNav ul').click(function () {
//-----^------^-------you have to remove quotes here.

Upvotes: 1

Related Questions