How to hide collapsible Bootstrap 4 navbar on click

Rudi Thiel picture Rudi Thiel · Feb 22, 2017 · Viewed 141.8k times · Source

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;
}

Answer

Zim picture Zim · Feb 22, 2017

You can add the collapse component to the links like this..

<ul class="navbar-nav mr-auto">
     <li class="nav-item active">
         <a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
     </li>
     <li class="nav-item">
         <a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
     </li>
 </ul>

Demo using 'data-toggle' method

Or, (perhaps a better way) use jQuery like this..

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

Demo using jQuery method

Update 2019 - Bootstrap 4

The navbar has changed, but the "close after click" method is still the same:

https://codeply.com/go/nFDHoEqqJQ (jQuery method)
https://codeply.com/go/PqIBtz3HPL (data-toggle method, see Bootstrap Collapse component)