Search code examples
javascriptjquerytoggleevent-bubblingmouseup

jQuery toggle and mouseup conflict


I have a simple button that toggles a menu onclick

If the menu is expanded/visible I hide it when clicking anywhere on the page (a part from the menu itself).

var menuBtn = $(".btn-menu"),
menuContainer = $(".menu"),
menuChildren = $(".menu").find("*");

menuBtn.on("click", function() {
    menuContainer.toggle();
});

$(window).mouseup(function(e){
    if(!menuContainer.is(e.target) && !menuChildren.is(e.target)){
        menuContainer.hide();
    }
});

When applying that function on mouseup, my toggle function no longer works. Menu will always stay open if clicking multiple times on the button (whereas it should hide & show).

jsfiddle here

Any idea how I could fix this?


Solution

  • mouseup event was fired before click. try this

    $(window).mouseup(function(e){
        if(!menuContainer.is(e.target) && !menuChildren.is(e.target) && !menuBtn.is(e.target)){
            menuContainer.hide();
        }
    });
    

    fiddle js