How to hide my collapse bootstrap 3 navbar with click on body when, collapse is visible?

前端 未结 7 548
攒了一身酷
攒了一身酷 2021-01-24 23:39

I\'m making a WordPress website for agency where I will go work. I used Bootstrap 3.0, and I created a responsive menu.

How to hide menu when is collapsed and visible (

7条回答
  •  有刺的猬
    2021-01-24 23:58

    You don't want to listen for the click all the time that is so wrong. you have to bind and unbind based on the navbar status. here is my navbar-colapse and it's id is 'z', and when it is open i will listen for clicks and when it's closed i don't listen anymore. i will put comment on the code:

        //CALLBACK AFTER NAVBAR-COLLAPSE OPEN
        $('#z').on('shown.bs.collapse', function () {
            // HERE WE BIND THE CLICK TO THE HANDLER FUNCTION
            $(document).bind( "click", handler );
        })
        //CALLBACK AFTER NAVBAR-COLLAPSE CLOSE
        $('#z').on('hidden.bs.collapse', function () {
            // SINCE THE NAVBAR IS CLOSED WE DONT NEED TO LISTEN FOR CLICKS           ANYMORE
            $(document).unbind( "click", handler );
        })
        //THIS IS THE FUNCTION THAT GET FIRED
        var handler = function() {
            //LISTEN FOR CLICKS
            $(document).click(function(event) {
                //HERE FORM-CONTROL IS MY SEARCH BOX IN THE NAV SO I DONT WANT TO CLOSE
                //THE NAVBAAR IF THEY CLICK ON FONT-CONTROL, BUT ANYTHING BESIDE THAT WE CLOSE THE NAVBAR
                if (!$(event.target).hasClass("form-control")) {
                    $('#z').collapse('hide');
                }
            });
        };  
    

    Also here is my nav-bar code :)

                
    

提交回复
热议问题