user1170330 user1170330 - 4 months ago 11
CSS Question

Menu should disappear when clicked somewhere else

I have a

div
which should be visible, whenever a button is clicked. It's like a menu. Afterwards, it should disappear (toggle), when the button is clicked again or when the user clicks somewhere else on the page (whole body).

In my current approach, the menu constantly toggles, so both functions (see below) are being triggered.

$("#b1").click(function() {
$("#menu").toggle("slide");
});

$("body").click(function() {
if ($("#menu").is(":visible")) {
$("#menu").toggle("slide");
}
});


How should I improve my code, so that the menu only disappears when the button is clicked again or when the user clicks somewhere else?

Here is a fiddle.

Answer

You can use e.target and check whenever it's not the menu or the button which got clicked. Otherwise the menu closed even on the button click or on a click inside.

$("#b1").click(function() {
    $("#menu").slideDown();
});

$("body").click(function(e) {
    if (!$(e.target).is("#b1") && $("#menu").is(":visible")) {
        $("#menu").slideUp();
    } else {
        e.preventDefault();
    }
});

If you want the menu to stay even on click inside, just add && !$(e.target).is("#menu") to the if condition.

Working example.

Comments