Closing the Bootstrap 5 Navbar on Click Event

I'm not very familiar with Bootstrap and I came across this code online that involves javascript in html, which I don't fully understand. I want to make the hamburger menu close automatically after selecting an item in the navigation bar, especially on mobile.

Is there anyone who can assist me with this?

GitHub repository

GitHub page

 <!-- Page Navbar -->
<nav class="custom-navbar" data-spy="affix" data-offset-top="20">
    <div class="container">
        <a class="logo" href="index.html">Portfolio</a>         
        <ul class="nav">
            <li class="item">
                <a class="link" href="#home">Home</a>
            </li>
            <li class="item">
                <a class="link" href="#about">About</a>
            </li>
            <li class="item">
                <a class="link" href="#portfolio">Portfolio</a>
            </li>
            <li class="item">
                <a class="link" href="#testmonial">Testimonial</a>
            </li>
            <li class="item">
                <a class="link" href="#blog">Blog</a>
            </li>
            <li class="item">
                <a class="link" href="#contact">Contact</a>
            </li>
            <li class="item ml-md-3">
                <a href="components.html" class="btn btn-primary">Components</a>
            </li>
        </ul>
        <a href="javascript:void(0)" id="nav-toggle" class="hamburger hamburger--elastic">
            <div class="hamburger-box">
              <div class="hamburger-inner"></div>
            </div>
        </a>
    </div>          
</nav><!-- End of Page Navbar -->

Answer №1

After tackling the issue head-on, I successfully resolved it. By utilizing jQuery's functionality, it became apparent that simply adding a command to trigger the function when a link is clicked was all that was needed to open the menu.

Answer №2

Although I'm not too familiar with Bootstrap logic, it appears that we can create a hamburger menu using only classes and Bootstrap attributes without the need for JavaScript on our part.

Take a look at the following example modified from the Bootstrap Docs (Navbar > Responsive Behaviors > Offcanvas navbar). I have added some comments to help clarify what the code is generating. I couldn't get the snippet below to work here on StackOverflow, but it functions correctly in CodePen.

As you can observe, the open/close functionality of the menu is achieved through the HTML attributes named data-bs-toggle, data-bs-target, and data-bs-dismiss. The first two attributes belong to the open menu button, while the last one is used to close the menu with the close menu button.

Within the links inside the menu, the data-bs-dismiss attribute is not present because it likely opens a different window. However, if your scenario keeps you within the same window, you may consider adding this attribute to the links as well.

I won't delve further into explaining this, as I also don't grasp all the details... but the key point is that it functions, presumably.

    <!--import Bootstrap-->
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8d80809b9c9b9d8e9fafdac1ddc1dc">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>

    <!-- Actual example -->
    <nav class="navbar bg-light fixed-top">
      <div class="container-fluid">
        
        <!-- Header Menu -->
        <a class="navbar-brand" href="#">Offcanvas navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
          <span class="navbar-toggler-icon"></span>
        </button>
        
        <!-- Inside the hamburguer menu -->
        <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel">
          
          <!-- Title and close button -->
          <div class="offcanvas-header">
            <h5 class="offcanvas-title" id="offcanvasNavbarLabel">Offcanvas</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
          </div>
          
          <!-- Menu items in an unordered list-->
          <div class="offcanvas-body">
            <ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
              <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
              </li>
            </ul>
            <form class="d-flex mt-3" role="search">
              <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
              <button class="btn btn-outline-success" type="submit">Search</button>
            </form>
          </div>
        </div>
      </div>
    </nav>

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

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

Printing Multiple Pages Using JavaScript and Cascading Style Sheets

Encountering difficulties displaying page numbers when printing multiple multipage reports Here is the provided HTML Format : <style type="text/css> body { counter-reset: report 1 page 0; } td.footer:after { counter-increment: page; content ...

Tips for concealing the top button on a mat calendar

I have a calendar for a month and year, but when I click on the top button it also displays the day. How can I hide that button or instruct the calendar not to show the days? Check out this image I was thinking of using a CSS class to hide that element. ...

Shifting an HTML anchor to account for a stationary header - Safari compatibility with alternative CSS styling

I made adjustments to my HTML anchors by adding an offset in the CSS to accommodate for a fixed header in my theme: margin-top: -175px; padding-top: 175px; } /* Adjustments for screen sizes of 760px and smaller */ @media (max-width:760px){ #r ...

Unable to align the row in the center

I'm having trouble centering a row with 4 columns. It seems off when I look at the picture below, specifically at the vertical border under the "most read" blue square. html file: <div class="block-section"> <div class="sm-section-wrapper" ...

Continuously replicate SVG horizontally without limit

In search of the perfect visual effect, I am eager to develop an infinite animation featuring a car moving horizontally with various landscape layers passing by in SVG format. Struggling to find a way to seamlessly repeat my SVG landscape layers along the ...

Tips for creating a vintage, weathered font appearance on a web browser

Is it possible to create unique, randomly outwashed letters using a standard font? Instead of relying on pre-designed outwashed fonts available at , I am interested in achieving the same effect with a regular font that appears washed out when displayed in ...

Attempting to transmit a ng-repeat object to a personalized filter function

Objective: The goal is to enable a user to input the name of a course into the search field and view a list of students who are enrolled in that course. Data Models: course (contains course name and code) student (holds a list of courses they are regist ...

Limited access textbox

Is there a way to create a text-box in AngularJS/HTML that is partially readonly? For instance, having the default value as "+91" and making it readonly while allowing users to enter additional values afterwards? ...

What is the purpose of the .php?action.. function?

I'm trying to understand the purpose of ?action=add&code= in the code snippet below. I've searched on Google, but all I found was information about HTML action attributes. <form method="post" action="index.php?action=add&code=<?php ...

Ways to incorporate radio buttons, checkboxes, and select fields into a multi-step form using JavaScript

In the snippet below, I have created a multi-step form where users can provide details. The issue is that currently only text input fields are being accepted. The array of questions specifies the type of input required for each question: Question no.1 req ...

Is there a way to include a minimize button on a MaterialUi Table enclosed in a Paper component for easy table reduction?

I am trying to add a minimize button to either minimize my MaterialUi Table or the Paper component that wraps it. Here is the code I have so far: <TableContainer component={Paper} style={{maxHeight:'inherit', maxWidth:'inherit', boxS ...

What is the best way to incorporate a third-party element into Vue using a script tag?

I am in the process of developing a website and I would like to include a widget that links to a podcast on BuzzSprout. Initially, I created the site using HTML to test out different designs, but now I am looking to transition it to VueJS. In my HTML vers ...

Introduction to Grid Layout Using Bootstrap - Rows

Encountering an issue with the vertical alignment of items in the code snippet below when using Bootstrap 4. Initially, the items are stacked vertically, but they align horizontally when either the "row" or "row align-items-start" classes are applied. &l ...

Set the background of the div element behind the image

I am trying to create a layout where the div color matches the size of an image behind it, with the image moving slightly on hover. Here is my code: <div class="row text-center about__gallery"> <div class="col-xs-12 col-sm-4"> <div cl ...

Exploring the file attributes within nw.js

I'm in the process of developing a native application using nw.js. I have included the following code snippet: <input id="fileDialog" type="file" accept=".pdf,.epub" multiple/><a id="add" href="#">Add</a> Below is my JavaScript cod ...

Using ReactJS to search for and replace strings within an array

A feature of my tool enables users to input a string into a textfield and then checks if any words in the input match with a predetermined array. If the user's string contains a specific name from the array, I aim to replace it with a hyperlink. I&a ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

Creating visually stunning full-width sections with graphic backgrounds using Bootstrap

Trying to bring a unique design concept to life, courtesy of my talented graphic designer. However, this sleek look is proving to be quite the challenge as I navigate through bootstrap implementation. We are focusing on a call to action section that perfe ...

Changing the color of text in an HTML input field using CSS and JavaScript depending on the input value

Looking for a solution! // Getting user input values var input1 = parseInt(document.getElementById("input1").value); var input2 = parseInt(document.getElementById("input2").value); var input3 = parseFloat(document.getElementById(" ...