Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide collapsible Bootstrap navbar on click

People also ask

How do you close an open collapse navbar when clicking outside the navbar element in bootstrap 4?

Currently, the only way to open or close it is by clicking on the navbar-toggle button.

How do I stop bootstrap navbar from collapsing?

For navbars that never collapse, add the . navbar-expand class on the navbar. For navbars that always collapse, don't add any .

How do I make bootstrap navbar-collapse?

To create a collapsible navigation bar, use a button with class="navbar-toggler", data-toggle="collapse" and data-target="#thetarget" . Then wrap the navbar content (links, etc) inside a div element with class="collapse navbar-collapse" , followed by an id that matches the data-target of the button: "thetarget".

How do I create a collapsible navbar in Bootstrap 5?

Very often, especially on small screens, you want to hide the navigation links and replace them with a button that should reveal them when clicked on. To create a collapsible navigation bar, use a button with class="navbar-toggler", data-bs-toggle="collapse" and data-bs-target="#thetarget" .


Update 2021 - Bootstrap 5 (beta)

Use javascript to add a click event listener on the menu items to close the Collapse navbar..

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
    l.addEventListener('click', () => { bsCollapse.toggle() })
})

BS5 demo javascript method

Or, Use the data-bs-toggle and data-bs-target data attributes in the markup on each link to toggle the Collapse navbar...

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
                </li>
            </ul>
            <form class="d-flex my-2 my-lg-0">
                <input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
        </div>
    </div>
</nav>

BS5 demo data-attributes method


Update 2019 - Bootstrap 4

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

BS4 demo jQuery method
BS4 demo data-toggle method


Bootstrap 3 (original answer)

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>

BS3 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');
});

BS3 demo using jQuery method


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"

<div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">
          <a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>
        </li>
      </ul>
</div>

You can call $.collapse('hide'); with an event handler on the links.

$('.nav-link').on('click',function() {
  $('.navbar-collapse').collapse('hide');
});
.navbar-toggler .icon-bar {
  margin: 7px;
  display: block;
  width: 22px;
  height: 1px;
  background-color: #cccccc;
  border-radius: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<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>

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.

$('.navbar-nav li a').on('click', function(){
    if(!$( this ).hasClass('dropdown-toggle')){
        $('.navbar-collapse').collapse('hide');
    }
});

this is the solution to close menu when click on anchor then apply this line in list item

     data-target="#sidenav-collapse-main" data-toggle="collapse"

the real example that work for me is below

      <li class="nav-item" data-target="#sidenav-collapse-main" data- 
      toggle="collapse" >
      <a class="nav-link" routerLinkActive="active" routerLink="/admin/users">
        <i class="ni ni-single-02  text-orange"></i> Users
      </a>
      </li>

The easiest way to do it using only Angular 2/4 template with no coding:

<nav class="navbar navbar-default" aria-expanded="false">
  <div class="container-wrapper">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
      <ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
      </ul>
    </div>

  </div>
</nav>

I am using Angular 5 with Boostrap 4. It works for me in this way.

 $(document).on('click', '.navbar-nav>li>a, .navbar-brand, .dropdown-menu>a', function (e) {
      if ( $(e.target).is('a') && $(e.target).attr('class') != 'nav-link dropdown-toggle' ) {
        $('.navbar-collapse').collapse('hide');
      }
    });
   }
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <a class="navbar-brand" [routerLink]="['/home']">FbShareTool</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarColor01">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active" *ngIf="_myAuthService.isAuthenticated()">
        <a class="nav-link" [routerLink]="['/dashboard']">Dashboard <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item dropdown" *ngIf="_myAuthService.isAuthenticated()">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Manage
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" [routerLink]="['/fbgroup']">Facebook Group</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item" href="#">Fetch Data</a>
          </div>
      </li>
    </ul>

    <ul class="navbar-nav navbar-right navbar-right-link">
        <li class="nav-item" *ngIf="!_myAuthService.isAuthenticated()" >
            <a class="nav-link" (click)="logIn()">Login</a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">
           <a class="nav-link">{{ _myAuthService.userDetails.displayName }}</a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated() && _myAuthService.userDetails.photoURL">
            <a>
              <img [src]="_myAuthService.userDetails.photoURL" alt="profile-photo" class="img-fluid rounded" width="40px;">
            </a>
        </li>
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">
            <a class="nav-link" (click)="logOut()">Logout</a>
        </li>
    </ul>

  </div>
</nav>