Ice Jungrai
Ice Jungrai

Reputation: 385

Why my drop down menu suddenly disappear after click for the first time?

You can see my live demo here. I want the drop down menu to display properly. Now it's suddenly hidden when first clicked. And I want to make drop down menu to be disappear when click anywhere outside drop down menu that is/are currently shown. How am I supposed to do that?

This is my jQuery code

$(document).ready(function () { 
    $('#jsddm > li').click(function(e){
        e.preventDefault();
        $(this).find('ul').eq(0).css('visibility', 'visible').slideToggle();
    });
});

I noticed that if .css('visibility', 'visible') is removed, the drop down menu will not work anymore.

Upvotes: 2

Views: 2153

Answers (3)

lamflam
lamflam

Reputation: 281

Since your function is only called when you click on the "li" element, clicking anywhere else in the document won't have any effect. You could add a click event to the entire body that hides the menu. To do this, you also need to stop the click event from the menu from bubbling up to the document, otherwise it will show and then hide instantly.

Try something like this:

$(document).ready(function () {

$('#jsddm > li').click(function(e){
      e.stopPropagation();
      e.preventDefault();
      $(this).find('ul').eq(0).slideToggle();
});

$(document).click(function (e) {
    $('#jsddm > li').find('ul').eq(0).slideUp();
});

});

You also don't need to use the visibility:hidden, it is just causing you to do more work. Here's the edit I made to the CSS along with the edited code above and it seems to be working in a local copy I made:

Replace

#menu #jsddm li ul{margin: 0; padding: 0; position: absolute; visibility: hidden; width:220px; z-index:9999;}

With

#menu #jsddm li ul{margin: 0; padding: 0; position: absolute; display:none; width:220px; z-index:9999;}

Upvotes: 4

tom
tom

Reputation: 91

Try setting "display" to "none" for all your tags at the very beginning.

$(document).ready(function () { 
   $('#jsddm > li > ul').css("display", "none");
   // ur code
}

Upvotes: 1

PhearOfRayne
PhearOfRayne

Reputation: 5050

Maybe you should check if its already visible or not first and then do your code. Something like:

$(document).ready(function () { 
    $('#jsddm > li').click(function (e) {
        e.preventDefault();
        if ($(this).find('ul').eq(0).is(':visible')) {
            $(this).find('ul').eq(0).slideUp();
        } else {
            $(this).find('ul').eq(0).slideDown();
        }
    });
});

Upvotes: 0

Related Questions