Search code examples
javascriptjquerytwitter-bootstrapmenusidebar

Close bootsnav side-menu on page click


newbie here),
I am using bootsnav to create a side menu with a toggle button. I want it to close if the user clicks somewhere else out of the menu, but i can't make it work. I tried several solutions that i found around the forums (there are many, really) but nothing. I tried to do things like this with jquery using toggleClass and removeClass, but the best attempt resulted in a menu that didn't open, because the toggle class triggered and untriggered at the same time.

This is the code that triggers the menu:

$("nav.navbar.bootsnav .attr-nav").each(function(){  
            $("li.side-menu > a", this).on("click", function(e){
                e.preventDefault();
                $("nav.navbar.bootsnav > .side").toggleClass("on");
                $("body").toggleClass("on-side");
            });
        });
        $(".side .close-side").on("click", function(e){
            e.preventDefault();
            $("nav.navbar.bootsnav > .side").removeClass("on");
            $("body").removeClass("on-side");
        });

Can anybody help, please?


Solution

  • You can create some element on your HTML as overlay background for your menu and show it when side menu is show, and hide it when side menu is hide like this

    $("nav.navbar.bootsnav .attr-nav").each(function(){  
        $("li.side-menu > a", this).on("click", function(e){
           e.preventDefault();
           $("nav.navbar.bootsnav > .side").toggleClass("on");
           $("body").toggleClass("on-side"); 
    
           $(".overlay-menu").fadeIn();
        });
    });
    $(".side .close-side").on("click", function(e){
        e.preventDefault();
        $("nav.navbar.bootsnav > .side").removeClass("on");
        $("body").removeClass("on-side");
    
        $(".overlay-menu").fadeOut();
    });
    

    Then you can create .overlay-menu as event close for .side-menu like this

    $(".overlay-menu").on("click", function(e){
       e.preventDefault();
       $("nav.navbar.bootsnav > .side").removeClass("on");
       $("body").removeClass("on-side");
    
       $(this).fadeOut();
    });
    

    set .overlay-menu on your css like this

    .overlay-menu{
       position:fixed;
       display:block;
       height:100%;
       width:100%;
       z-index: (less from side-menu)
    }
    

    Hope this help you