JS_basic_knowledge
JS_basic_knowledge

Reputation: 117

Close drop down menu when clicking outside menu

I have the following

function subNavToggle() {
    var subNav = document.getElementById("subnav-section");
    if (subNav.className === "navigation-subnav") {
        subNav.className += " responsive";
    } else {
        subNav.className = "navigation-subnav";
    }
 }

I am trying to get the expanded menu to close when clicking outside of menu.

I have this, which will close the menu, but it also closes the hamburger menu - preventing the user to be able to open again.

 $(document).click(function(event) { 
     var $target = $(event.target);
     if(!$target.closest('.sub_nav_links').length && 
     $('.sub_nav_links').is(":visible")) {
       $('.sub_nav_links').hide();
     }        
   });

Also thought I could get away with the following, but it actually does the opposite. Opening outside menu item.

window.onclick = subNav;

Upvotes: 0

Views: 476

Answers (2)

pixelcreated
pixelcreated

Reputation: 196

  $('html').on('click, touchend', function (e) {
    // Close hamburger menu when tapping outside
    if ($(e.target).closest('#subnav-section').length == 0) {
        var opened = $('.navigation-subnav').hasClass('responsive');
        if (opened === true) {
            $('.navigation-subnav').collapse('hide');
        }
    }
});

Upvotes: 2

Saif Ullah
Saif Ullah

Reputation: 3077

// to hide
$(document).click(function(){
 $("#submenu").hide();
});

// you could possibly prevent to hide menu while using navigation
$("#menu").click(function(e){
 e.stopPropagation();
});

Upvotes: 0

Related Questions