I've created this collapsable navbar using Bootstrap 4 that works nicely, but I would like it to close when the user clicks on a link. Any way to do this? Thanks
html navbar:
<nav class="navbar navbar-toggleable-md fixed-top">
<button id="nav-btn"class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv" aria-expanded="false" aria-label="Toggle navigation">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="container">
<a class="navbar-brand" href="#"><img src="Images/logo.png" width="60px"></a>
<div class="collapse navbar-collapse" id="navbarDiv">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about-us">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#pricing">Pricing</a>
</li>
</ul>
</div>
</div>
</nav>
css for .icon-bar, since Bootstrap 4 doesn't use the icon-bar class.
.navbar-toggler .icon-bar {
margin: 7px;
display: block;
width: 22px;
height: 1px;
background-color: #cccccc;
border-radius: 1px;
}
You can add the
collapse
component to the links like this..Demo using 'data-toggle' method
Or, (perhaps a better way) use jQuery like this..
Demo using jQuery method
Update 2018 Bootstrap 4.0.0
The navbar has changed, but the
click after close
method is still the same:https://www.codeply.com/go/nFDHoEqqJQ
With trying out above solutions, I was missing a solution for Dropdown toggles, so here you go! Also opens submenu items.
Maybe you have to tweak it a bit if your toggle class is different.
The easiest way to do it using only Angular 2/4 template with no coding:
You can call
$.collapse('hide');
with an event handler on the links.I am using ANGULAR and since it gave me problems the routerLink just add the data-toggle and target in the li tag.... or use jquery like "ZimSystem"
I am using Angular 5 with Boostrap 4. It works for me in this way.