0

I have a dropdown menu using a html list. The jquery code works fine at the first level, but when i try to click something on the list with a submenu it closes and reopens the same list.

How can I get it to open everything but the list i clicked?

    // Document Listening
$(document).ready(function () {

    // JQuery running fine, don't need CSS trick for dropdown
    // Remove the class of child and grandchild, this removes the CSS 'falback'
    $("#nav ul.child").removeClass("child");
    $("#nav ul.grandchild").removeClass("grandchild");

    // When a list item that contains an unordered list is hovered on
    $("#nav li").has("ul").click(function (e) {
        $("#nav li").children("ul").not(e.target).slideUp("fast");
        $(this).children("ul").slideDown("fast");
    });

});

// Document Click 
// Click on anything else other then the link you clicked and close
$(document).mouseup(function (event) {
    if (!$(event.target).closest("#nav li").length) {
        $("#nav li").children("ul").slideUp("fast");
    }
});
g00n3r
  • 135
  • 12

1 Answers1

0

This is caused because when you click on a submenu, the event is fired for both the clicked li and the parent li. Calling stopPropagation will prevent that.

In addition, when you click on a child li, you slide up all li's other than the clicked li, which also slides up the parent. Change the .not statement to exclude the target and all parents.

$("#nav li").has("ul").click(function (e) {
    $("#nav li").children("ul").not($(this).parents()).slideUp("fast");
    $(this).children("ul").slideDown("fast");
    e.stopPropagation();
});

Here's a working fiddle: http://jsfiddle.net/qnzsS/1/

Turch
  • 1,546
  • 2
  • 15
  • 31