Hide Twitter Bootstrap nav collapse on click
try this:
$('.nav a').on('click', function(){
$('.btn-navbar').click(); //bootstrap 2.x
$('.navbar-toggle').click(); //bootstrap 3.x by Richard
$('.navbar-toggler').click(); //bootstrap 4.x
});
I just replicate the 2 attributes of the btn-navbar
(data-toggle="collapse" data-target=".nav-collapse.in"
) on each link like this:
<div class="nav-collapse">
<ul class="nav" >
<li class="active"><a href="#home" data-toggle="collapse" data-target=".nav-collapse.in">Home</a></li>
<li><a href="#about" data-toggle="collapse" data-target=".nav-collapse.in">About</a></li>
<li><a href="#portfolio" data-toggle="collapse" data-target=".nav-collapse.in">Portfolio</a></li>
<li><a href="#services" data-toggle="collapse" data-target=".nav-collapse.in">Services</a></li>
<li><a href="#contact" data-toggle="collapse" data-target=".nav-collapse.in">Contact</a></li>
</ul>
</div>
In the Bootstrap 4 Navbar, in
has changed to show
so the syntax would be:
data-toggle="collapse" data-target=".navbar-collapse.show"
$(function() {
$('.nav a').on('click', function(){
if($('.navbar-toggle').css('display') !='none'){
$('.navbar-toggle').trigger( "click" );
}
});
});
Better to use default collapse.js methods (V3 docs, V4 docs):
$('.nav a').click(function(){
$('.nav-collapse').collapse('hide');
});