user2907241
user2907241

Reputation: 265

JS Dropdown menu not closing?

So I found this fiddle here: http://jsfiddle.net/8qPvp/4/ I thought I'd use it just for personal education purposes. I'm really new with JS, and I noticed that the opened parent does not go back on click, like it opens. How could this be fixed?

$(document).ready(function () {
    $("li").click(function () {
        $('li > ul').hide();
        $(this).children("ul").toggle();
    });
});

Upvotes: 0

Views: 129

Answers (2)

nkmol
nkmol

Reputation: 8091

What about this:

$("li").click(function () {
    $('li > ul').hide();
    $(this).children("ul").toggle();
});

$(document).click(function()
{
    $('li > ul:visible').hide();
})

$('.menu li').click(function(e)
{
    e.stopPropagation();          
})

So by default i make whenever there is clicked ANYWHERE in the document, your visible menu will be hidden. However you don't want this to happen when you open a new menu(would be; made visible and made hiden directly). So i make a exception that catch when you want to open a new menu and i'll cancel the document click event.
I use event.stopPropagation() to cancel a event.

jsFiddle

Upvotes: 1

N8FURY
N8FURY

Reputation: 10010

$(document).ready(function () {
    $("li").click(function () {
        $('li > ul').hide();
        $(this).children("ul").toggle();
    }).mouseleave(function(){
        $(this).children("ul").hide();
    });
});

Check this fiddle http://jsfiddle.net/Aveendra/8qPvp/18/

Upvotes: 1

Related Questions