Search code examples
jqueryoverlaymegamenu

Prevent overlay from closing when click is in mega menu


The mega menu and overlay is launched when you click #mega-dropdown. When you click whitespace within the mega menu, the overlay is hidden. I'd like to prevent this.

Here's my simplified markup:

<ul class="nav navbar-nav">

  <!-- Click Here -->
  <li class="dropdown mega-dropdown" id="mega-dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="category">Mega Menu</a>

    <!-- Show this mega menu -->    
    <ul class="dropdown-menu mega-dropdown-menu row" id="mega-dropdown-menu">
      <li>Mega Menu Content</li>
    </ul>
  </li>
</ul>

Here's my current JS:

$(document).ready(function(){
    // Activate Overlay when Mega Menu is Open
    $(document).on('click', function(){
        var clicked = $(e.target);
        if (clicked.is('.mega-dropdown-menu') || clicked.parents().is('.mega-dropdown-menu')) {
            return; 
       } else { 
         $('#overlay').removeClass('open');
       }
    });

    $('#mega-dropdown').on('click', function(){
        if($('#mega-dropdown-menu').is(":visible") ) {
            $('#overlay').removeClass('open');
        } else {
            $('#overlay').addClass('open');
        }
    });

});

// Prevent the menu from closing if user clicks inside the contianer
jQuery(document).on('click', '#mega-dropdown', function(e) {
  e.stopPropagation();
})

Solution

  • The reason the overlay is going away is because you are closing it. The mega-dropdown click handler should be the following:

      $('#mega-dropdown').on('click', function(e){
        if(!$('#mega-dropdown-menu').is(":visible") ) {
          $('#overlay').addClass('open');
        }
      });