1

I wanted to close the navbar click outside of it then I used this code

$(document).on('click',function(){              
        if(!$('#top_right_menu_btn').hasClass('open')) {
            $('#myNavbar').collapse('hide');
        }

    });  

but it closes drop down menu even click on it, so I want to prevent from closing when clicking on it.

my site (nav bar will appear when screen size below 768px)

Sahan Perera
  • 194
  • 2
  • 5
  • 17

1 Answers1

1

There are a few errors in the other answer but I have updated it below.

You need to run .collapse() on the navbar, not the toggle button.

$(".navbar-collapse").collapse('toggle');

Also you need to make sure that the click does not happen within the .navbar element.

!$(event.target).closest('.navbar').length

All together:

$(document).ready(function () {
    $(document).click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".navbar-collapse").hasClass("in");
        if (!$(event.target).closest('.navbar').length && _opened === true && !clickover.hasClass("navbar-toggle")) {
            $(".navbar-collapse").collapse('toggle');
        }
    });
});

Example plnkr

machinehead115
  • 1,647
  • 10
  • 20