Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to make it so that my dropdown menu shows when you click a button, and hides when you click anywhere except the dropdown menu.

I have some code working, as far as not closing when you click the menu, however when you click the document when the menu is closed, it shows the menu, so it continuously toggles no matter where you click.

$(document).click(function(event) {
    if ($(event.target).parents().index($('.notification-container')) == -1) {
        if ($('.notification-container').is(":visible")) {
            $('.notification-container').animate({
                "margin-top": "-15px"
            }, 75, function() {
                $(this).fadeOut(75)
            });
        } else {
            //This should only show when you click: ".notification-button" not document
            $('.notification-container').show().animate({
                "margin-top": "0px"
            }, 75);
        }
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
296 views
Welcome To Ask or Share your Answers For Others

1 Answer

jQuery's closest() function can be used to see if the click is not within the menu:

$('body').click(function(e) {
    if ($(e.target).closest('.notification-container').length === 0) {
        // close/animate your div
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...