Skip to content
Advertisement

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);
        }
    }
});

Advertisement

Answer

This is what I’ve decided to use, it’s a nice little jQuery plugin that works with little code.

Here’s the plugin: http://benalman.com/projects/jquery-outside-events-plugin/

This is the code that makes my above code in my question work.

$(document).ready(function(){
    $(".notification-button").click(function(){
        $('.notification-container').toggle().animate({"margin-top":"0px"}, 75); 
    }); 

    $('.notification-wrapper').bind('clickoutside', function (event) {
        $('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
    });
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement