You might be trying to relocate the navbar to the right or left side of the layout. For left and right sidebar or navbars closing them by clicking outside is a good functionality.
Javascript Method (Personally I don’t do this)
$(document).ready(function () {
$(document).click(function () {
// if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
// }
});
});
CSS Method
You will need 1 line of html code and few lines of CSS.
HTML
<!-- Add this line above navbar -->
<a class="close-navbar-toggler collapsed" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
</a>
CSS
.navbar{
/* z-index should be above .close-navbar-toggler */
z-index:2;
}
.close-navbar-toggler{
position:absolute;
top:0;
left:0;
height:100%;
width:100%;
z-index:1;
cursor:pointer;
}
.close-navbar-toggler.collapsed{
z-index:-1;
}
View the Codepen to understand better
See the Pen Close Bootstrap open collapse navbar clicking outside of navbar by KiranWorkspace (@kiranworkspace) on CodePen.