Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide dropdown when clicked anywhere but menu

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);
        }
    }
});
like image 884
Dylan Cross Avatar asked Jan 10 '12 08:01

Dylan Cross


3 Answers

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
    }
});
like image 115
epoch Avatar answered Nov 18 '22 00:11

epoch


you can do something like this if your item is not clicked then hide its dropping list in case of drop down

$(':not(#country)').click(function() {
     $('#countrylist').hide();
});
like image 7
Bipin Chandra Tripathi Avatar answered Nov 17 '22 23:11

Bipin Chandra Tripathi


I am using a very simple code for this as :-

$(document).click(function(e){

   if($(e.target).closest('#dropdownID').length != 0) return false;
   $('#dropdownID').hide();
});

Hope it will useful.

Thanks!!

like image 5
Vishnu Choudhary Avatar answered Nov 18 '22 00:11

Vishnu Choudhary