JQuery if click outside the element hide but also show/hide if cliked on a button

Viewed 29

I'm struggling with a problem here. I have two elements. One is a button and other is a menu. I need to solve a problem which occurs to me when I click on the button first time, menu opens, but when I click second time it doesn't. And when I click outside the menu it closes (that's good!). SO I need the element to close/open on click's with a button and clicking outside the element.

Here's my code:

$(".left-menu-block-one").click(function () {
    $("#first-bar").toggleClass("show");
    if ($("#second-bar").hasClass("show") || $("#third-bar").hasClass("show")) {
        $("#second-bar").removeClass("show");
        $("#third-bar").removeClass("show");
    }
    $(".left-menu-block-one").toggleClass("hide-menu-bars");
    if ($("#first-bar").hasClass("show")) {
        $(".left-menu-block-two").addClass("hide-menu-bars");
        $(".left-menu-block-three").addClass("hide-menu-bars");
    }
})
var container2 = $("#first-bar");
if (!container2.is(e.target) && container2.has(e.target).length === 0) 
{
    $("#first-bar").removeClass("show");
    $(".left-menu-block-one").addClass("hide-menu-bars");

}

P.S. I added all code for those 2 elements, because maybe there is a problem with them...

1 Answers

Conceptually do this:

When the user clicks on the button your code will toggle the popup/element between showing and hidden. (You code probably already does this.)

When the popup/element is changed to showing then add a click event listener on document using 'capture' mode.

In this new event handler:

  1. If the user clicks on your popup/element, its children or the original button that opened the popup/element then do nothing.
  2. If they click on anything besides your popup/element or the original button then toggle the popup/element back to hidden and remove the event listener on document.
Related