Search code examples
javascriptjqueryhamburger-menu

Hide mobile menu on click anywhere on a website


I have one problem, I want to hide the menu on click anywhere on the website, but nothing works for me :( Here is my code for closing button:

$('.menu-toggle').on('click',function(e){
        e.preventDefault();
        if ( $('.lang-mobile').hasClass('is-open') ){
            $('.lang-mobile a').trigger('click')
        }
        if ( !$('header').hasClass('is-open')){
            $('header').addClass('is-open');
            $('#navbar-main').fadeIn();
        }
        else {
            $('header').removeClass('is-open');
            $('#navbar-main').fadeOut();
        }

Here is some of my HTML structure

<header class="header clear is-open" role="banner">

    <div class="navbar" id="navbar-main" style="display: block;">
<div class="navbar-container" style="height: 797px;">
<div class="navbar-item">

I've tried something like this

    $(document).click(function() {
    var container = $("#navbar-main");
    if (!container.is(event.target) && !container.has(event.target).length) {
        container.hide();
    }
});

and it's not working, could you please help me? What is incorrect here?


Solution

  • Thank you Youssouf Oumar for sharing this link as an answer - Mobile Menu - Click outside menu to close menu this the only thing that worked for me! I only added some needed parts to this code, so here you go if anyone noob like me and needs more details :D

    $(document).mouseup(function(e){
       var header = $ (".header, .lang-mobile"); //I have two toggle menus with class that collapse navbars, I also have animation on toggle button that's why I need them also to work
       var menu = $(".navbar, .dropdown");//this is to hide menus 
       if (!menu.is(e.target) // The target of the click isn't the container.
       && menu.has(e.target).length === 0) // Nor a child element of the container
       {
          header.removeClass('is-open');
          menu.hide(); 
       }
    });