skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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(); 
       }
    });
    

  2. This snippet handles two cases.

    • Every time there’s a click on the page it’ll check if the header is open and close it
    • Every time there’s a click on the .menu-toggle item it’ll open or close the header
    <script>
        $(document).on('click', function() {
            var header = $(".header");
            if ( header.hasClass('is-open') ) {
                header.fadeOut();
                header.removeClass('is-open');
            }
        });
    
        $('.menu-toggle').on('click', function() {
            var header = $(".header");
            if ( !header.hasClass('is-open') ) {
                header.fadeIn();
                header.addClass('is-open');
            } else if ( header.hasClass('is-open') ) {
                header.fadeOut();
                header.removeClass('is-open');
            }
        });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search