Home > Back-end >  Trying to close popup by clicking outside of div breaks button that opened it
Trying to close popup by clicking outside of div breaks button that opened it

Time:12-23

I have a mobile/responsive nav menu that is opened with a button using jquery. The button was working great until I added a jquery script to also close the window if the user clicks anywhere outside of the menu div, that script also works as intended to close the menu everywhere except when attempting to use the initial menu button, which won't function if I try to close the menu with it (but can still be used to open the menu again if its closed).

Anyone able to help me figure out why the button itself isnt working?

  $(document).ready(function() {
    var mobileNav = $('#mobile-nav');

    //Toggle hide on the menu
    $('.btn-navbar').on('click', function(){
      mobileNav.toggleClass('d-none');
    });

    // Hide menu if clicked outside
    $(document).mouseup(function(e){
      if (!mobileNav.is(e.target) && mobileNav.has(e.target).length === 0 && !mobileNav.hasClass('d-none')){
        $('#mobile-nav').toggleClass('d-none');
      }

    });
     
  });

CodePudding user response:

i'm not certain of the why but the button doesn't like the $(document) declaration ... i'm now using the same function but using the id of the main content div

CodePudding user response:

Since mouseup event fires before click event, so when you click on .btn-navbar actually first the handler related to mouseup runs, and it toggles the class d-none on mobileNav, after that the handler related to click runs, and it again toggles the d-none class on mobileNav, so as a result it's display never changes, to solve them problem,in the mouseup handler you can check if the target element is not .btn-navbar then toggle d-none class, like this:

$(document).mouseup(function(e){
  if (!$(e.target).is('.btn-navbar') && !mobileNav.is(e.target) && mobileNav.has(e.target).length === 0 && !mobileNav.hasClass('d-none')){
    $('#mobile-nav').toggleClass('d-none');
  }
});

Here is a simple example:

$(document).ready(function() {
  var mobileNav = $('#mobile-nav');

  //Toggle hide on the menu
  $('.btn-navbar').on('click', function() {
    mobileNav.toggleClass('d-none');
  });

  $(document).mouseup(function(e) {
    if (!$(e.target).is('.btn-navbar') && !mobileNav.is(e.target) && mobileNav.has(e.target).length === 0 && !mobileNav.hasClass('d-none')) {
      $('#mobile-nav').toggleClass('d-none');
    }
  });

});
.d-none {
  display: none
}

#mobile-nav {
  background: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button >Toggle nav</button>
<h1 id="mobile-nav" >nav content</h1>

  • Related