Łukasz Trocha Łukasz Trocha - 6 months ago 65
Javascript Question

How to fix blinking navbar after click

I tried to use this solution (Hide Twitter Bootstrap nav collapse on click) to hide nav collapse automatically when clicking. It's working correctly when nav is collapsed but when I'm using site on desktops (exactly when nav is not collapsed) nav is blinking.

Code:



$('.nav a').on('click', function() {
$(".btn-navbar").click(); //bootstrap 2.x
$(".navbar-toggle").click() //bootstrap 3.x by Richard
});

.block {
padding: 70px 0;
}
#section-white {
background-color: #fff;
height: 100px;
}
#section-1 {
margin-top: 51px;
/* height of header-navbar */
}
#section-1,
#section-2,
#section-3 {
height: 600px;
background-color: #555;
color: #fff;
}

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a class="page-scroll" href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#section-1">About</a>
</li>
<li>
<a class="page-scroll" href="#section-2">Services</a>
</li>
<li>
<a class="page-scroll" href="#section-3">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>

<div class="block" id="section-1">
<div class="container">
<div class="row">
Hello World
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /.block -->

<div id="section-white"></div>

<div class="block" id="section-2">
<div class="container">
<div class="row">
Hello World
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /.block -->

<div id="section-white"></div>

<div class="block" id="section-3">
<div class="container">
<div class="row">
Hello World
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /.block -->





You can try it here - Desktop results and this is source code - source code

Earlier I used this solution in Bootstrap 2.3.2 and haven't got any problem.

Answer

Try this:

JS

$('.nav a').on('click', function() {
    $('.navbar-collapse').collapse('hide');
});

Check the updated fiddle.

Also check this answer: Close responsive navbar automatically