Click to collapse the Bootstrap navbar

Is there a way to collapse the Bootstrap nav bar when a user clicks on a nav-bar button instead of it staying open?

<nav class="navbar navbar-default" role="navigation">
  <div class="container-fluid">
    <div class="navbar-header">
      <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">Brand</a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li class="active"><a data-toggle="tab" href="#sectionA">Page1</a></li>
        <li><a data-toggle="tab" href="#sectionB">Page2</a></li>
        <li><a data-toggle="tab" href="#sectionC">Page3</a></li>
       </ul>
    </div>
  </div>
</nav>

Screenshot:

This is how the nav-bar looks after clicking on a button (it stays open):

This is how I would like it to be after clicking on a button (back to its original state):

Answer №1

Here are two ways to solve this issue:

Option 1: Utilize the data-toggle attribute

To make your menu collapse when a menu item is selected, simply add

data-toggle="collapse" data-target=".in"
to the anchor elements.

See below for an example code snippet:

    <nav class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
        <div class="navbar-header">
          <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">Brand</a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <ul class="nav navbar-nav navbar-right">
<!-- Add data-toggle="collapse" data-target=".in" to <a> elements-->
<!-- This way they will collapse the responsive menu when clicked -->
            <li class="active"><a data-toggle="collapse" data-target=".in" href="#sectionA">Page1</a></li>
            <li><a data-toggle="collapse" data-target=".in" href="#sectionB">Page2</a></li>
            <li><a data-toggle="collapse" data-target=".in" href="#sectionC">Page3</a></li>
           </ul>
        </div>
      </div>
    </nav>

Check out an example here: http://jsfiddle.net/Frondor/sey4wsah/


Option 2: Use jQuery as a more effective method

If the first option doesn't work for you, consider adding some jQuery lines after including the jQuery and Bootstrap.js libraries:

<script src="/js/jquery.min.js"> <!--Assuming these are the correct paths -->
<script src="/js/bootstrap.min.js">

Add the following jQuery code below:

<script>
$(document).ready(function () {
    $("nav").find("li").on("click", "a", function () {
        $('.navbar-collapse.in').collapse('hide');
    });
});
</script>

This script will automatically collapse your responsive menu whenever a link is clicked. Give it a shot!

Answer №2

Place the file named bootstrap.min.js in the js directory, and include the following line

<script src="js/bootstrap.min.js"></script>
just before the closing </body> tag. Also, store the file called bootstrap.min.css in the css folder, and insert this code
<link rel="stylesheet" href="css/bootstrap.min.css">
right before the closing </head> tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to remove horizontal scrolling and reduce element size on mobile devices?

My current project is utilizing the Material-ui framework, and I have a situation where numerous anchor elements are being displayed as a table within a Paper component from mui. However, due to the length of this table, it causes a horizontal scroll bar t ...

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

Ways to perfectly position a bootstrap well in the center

https://i.sstatic.net/b3g46.pnghttps://i.sstatic.net/osPzb.png Having trouble aligning this image with the center of the page. It should be a straightforward task, but for some reason, I can't seem to get it right. ...

Bootstrap 4 opts for a different approach by not incorporating a hamburger menu and avoiding the collapse of the

When utilizing this HTML code: <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>app</title> <meta name="description" content="to ...

Text cannot be highlighted within DIV element

Check out this page and this page on my website. Text within the advert DIV tag cannot be selected, and some text in the Incinerator product page is unselectable in the topic-div above the iframe element containing a YouTube video. Here is the relevant HT ...

Guide on finding and replicating a particular string in HTML connected websites

Allow me to outline the issue at hand. By visiting the provided link, you will encounter a directory of html links containing stories by Aesop, each with its own moral. My goal is to extract and save only the strings that include "Moral of Aesop's Fab ...

Is there a way to determine the quantity of items within a sortable div?

In my HTML document, there are multiple divs containing smaller divs that can be rearranged within each other. Upon loading the document, a random assortment of these smaller divs are added to #boxtop. Below is a snippet of my HTML code: <html> &l ...

How can I delete the header and footer on a personalized homepage design?

After crafting a unique home page/landing page for my website that stands out from the rest, I've come across an issue. The header and footer are appearing on this new page, but I only want to display what I specifically coded. I attempted using Site ...

The precedence of theme CSS is paramount

Check out this link for Smirnoff Espresso Vodka 70cl (password: hide) Upon inspecting the page source, you'll see that my main stylesheet (main-style) is loaded at the top of the head section with high priority, even above my theme's style. Why ...

Changing Content Dynamically in Adobe Muse

I'm in the process of creating a website for an internet radio station and I've chosen to use Adobe Muse due to its user-friendly design features. My goal is to have the header and footer sections stay static while only the content on the page ch ...

PHP code isn't showing any posts

Context: I have implemented a PHP loop to generate a dynamic feed of my portfolio posts on my WordPress website. Issue: The first five posts are being displayed correctly, but the subsequent posts are not. I'm uncertain about the underlying cause and ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

Adding Information to a Material Design Card

Currently, I am delving into frontend development and honing my CSS skills. In my latest project, I have incorporated a mat card which can be viewed in the linked image https://i.sstatic.net/TEDcg.png. Below is an excerpt of my code: <div class=&quo ...

Show unique language text in the <noscript> element based on the user's browser language

I am just starting out with HTML, and I would like to show a message if JavaScript is disabled. To do this, I have placed the message within the <noscript> tag, which is working perfectly. <noscript> Need to enable Javascript. </noscript> ...

Contrasts between space and the greater than selector

Can you explain the distinction between selector 6 and selector 7 as outlined on the w3 website? Inquiring minds want to know. ...

The function setCustomValidity() will continue to display even after the form has been successfully filled out

My form is very simple and I am trying to validate it using the required attribute: <form name="form"> <label for="Header">Title</label> <input type="text" class="span5" name="Header" ng-model="Message.header" placeholder="Title" on ...

CSS - The Failure of Implementing Multiple Segmented Controls

Recently, I came across a fantastic segmented control on and I am looking to customize it to fit my requirements. However, I encountered an issue where adding multiple controls to the page only affects the first segmented control. Instead of duplicating ...

Tips for avoiding Bootstrap collapse overflow within a container that has overflow-y-scroll

I'm currently facing an issue with a container that has the overflow-y-scroll CSS property. Inside this container, there's a Bootstrap collapse button that expands to show more content when clicked. The problem arises when the expanded content ov ...

Utilize a function within styled-components

I am looking to dynamically adjust the font size of a button based on the length of a passed-in prop. However, I can't use a dynamic width due to a custom animation applied to the component. Here is my current code: const checkLength = () => { i ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...