How to hide offcanvas navigation bar with one click in Bootstrap 5

There was an issue with a Bootstrap 5 project where the offcanvas menu would remain open after clicking on an anchor link.

Is there a way to automatically close the offcanvas menu after clicking on an anchor link?

 <nav class="navbar  fixed-top py-5 ">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">

                        <img src="photo.jpeg" alt="Image"
                            class=" image img-fluid rounded-circle position-absolute top-100 start-50 translate-middle ">

                    </a>
                    <div style="position: fixed; width: 100%; z-index: 1;">
                        <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas"
                            data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
                            <span class="navbar-toggler-icon"></span>
                        </button>
                    </div>
                    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar"
                        aria-labelledby="offcanvasNavbarLabel">
                        <div class="offcanvas-header">
                            <h5 class="offcanvas-title" id="offcanvasNavbarLabel">Index</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="offcanvas"
                                aria-label="Close"></button>
                        </div>
                        <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" >Home</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#service-section">Services</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#work-section">Works</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#contact-section">Contact</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link" href="#moreinfo-section">More Info</a>
                                </li>

                            </ul>

                        </div>
                    </div>
                </div>
            </nav>
        

Answer №1

Here is a potential resolution.

const menuItems = document.querySelectorAll('.menu-item');
const toggleMenu = document.querySelector('#menuTrigger');
menuItems.forEach((item) => {
  item.addEventListener('click', () => {
    $("button.nav-menu-toggle").click();
  });
});
<script src="https://code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7974746f686f697a6b5b2e3529352b">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15777a7a61666167746555203b273b25">[email protected]</a>/dist/css/bootstrap.min.css"></link>

<nav class="navbar  fixed-top py-5 ">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">

      <img src="photo.jpeg" alt="Image"
           class=" image img-fluid rounded-circle position-absolute top-100 start-50 translate-middle ">

    </a>
    <div style="position: fixed; width: 100%; z-index: 1;">
      <button class="nav-menu-toggle" type="button" data-bs-toggle="offcanvas"
              data-bs-target="#offcanvasMenu" aria-controls="offcanvasMenu">
        <span class="nav-menu-toggle-icon"></span>
      </button>
    </div>
    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasMenu"
         aria-labelledby="offcanvasMenuLabel">
      <div class="offcanvas-header">
        <h5 class="offcanvas-title" id="offcanvasMenuLabel">Index</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"
                aria-label="Close"></button>
      </div>
      <div class="offcanvas-body">
        <ul class="navbar-menu justify-content-end flex-grow-1 pe-3">
          <li class="menu-item">
            <a class="menu-link active" aria-current="page"  href="#Home" onclick="close_offcanvas()">Home</a>
          </li>
          <li class="menu-item">
            <a class="menu-link" href="#service-section">Services</a>
          </li>
          <li class="menu-item">
            <a class="menu-link" href="#work-section">Works</a>
          </li>
          <li class="menu-item">
            <a class="menu-link" href="#contact-section">Contact</a>
          </li>
          <li class="menu-item">
            <a class="menu-link" href="#moreinfo-section">More Info</a>
          </li>

        </ul>

      </div>
    </div>
  </div>
</nav>

The html remains the same except for the initial 3 lines (and the elimination of an additional </div> at the end).

Answer №2

No HTML was altered in any way, just the inclusion of three lines of jQuery code.

$("#offcanvasNavbar a").click(function(){
    $('.offcanvas').offcanvas('hide');
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8eece1e1fafdfafceffecebba0bca0bc">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8eece1e1fafdfafceffecebba0bca0bc">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">

<nav class="navbar  fixed-top py-5 ">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">

      <img src="photo.jpeg" alt="Image"
           class=" image img-fluid rounded-circle position-absolute top-100 start-50 translate-middle ">

    </a>
    <div style="position: fixed; width: 100%; z-index: 1;">
      <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas"
              data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
    </div>
    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar"
         aria-labelledby="offcanvasNavbarLabel">
      <div class="offcanvas-header">
        <h5 class="offcanvas-title" id="offcanvasNavbarLabel">Index</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"
                aria-label="Close"></button>
      </div>
      <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" onclick="close_offcanvas()">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#service-section">Services</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#work-section">Works</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#contact-section">Contact</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#moreinfo-section">More Info</a>
          </li>

        </ul>

      </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

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

Is there a way to unselect a button in Angular?

I have a set of buttons representing different categories. When I click on a button, it displays a card with relevant information. <app-category-button [label]='category.name' [isSelected]='category.id === (selectedCategoryId$ | asy ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

What could be the reason for the appearance of Next.js compile indicator in my final production build?

Upon completing the development and deployment of a Next.js website, I observed that the black compile indicator continued to appear in the bottom-right corner of my browser, similar to its presence during local development. The indicator can be viewed he ...

Obtaining Google AAID Using a Mobile Browser (JavaScript)

I've been looking for information online without much success regarding this topic. I am interested in retrieving a user's Google Advertising ID (AAID) through my website when they visit using a mobile browser. I assume it could be done with som ...

Encountering a 400 error when utilizing the Google Translate free API with Curl

I am attempting to utilize the free Google Translate API that is derived from Firefox's S3 Google Translator addon, by incorporating the following code: https://translate.google.com/translate_a/single?client=t&sl=auto& tl=en&hl=en&dt= ...

Using AJAX to get the response from a static [webmethod] - a guide

On my Default.aspx page, I have the following PageMethod: [WebMethod] public static string Hello() { return "Hello"; } I want to set the text of a div to whatever is returned via AJAX: <div id="ajaxDiv"></div> Below are two methods I us ...

Is it possible to have several users using JW Player simultaneously?

Struggling to incorporate multiple players using JW Player. I've attempted various methods and consulted the documentation, but I can't seem to pinpoint why the code is malfunctioning. Check out the snippets below: In the head section: <scr ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...

Exploring ways to access global window variables in React using JavaScript

I've been following the discussion on how to transfer variables from JavaScript to ReactJS. Here is my array of objects in JavaScript: window.dataArr = []; function makeJsObj(descr, currDate, done) { var data = {}; console.log(descr ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

The enigmatic jQuery AJAX glitch is craving additional arguments

My website uses jQuery's ajax function to handle user signups. Despite using similar code throughout the site, I encountered an error while trying to execute the code below: Error Message: uncaught exception: [Exception... "Not enough arguments" nsr ...

Making jquery's one() function work effectively with duplicated classes

Take a look at the following HTML code snippet: <div class="options-selecter"> <span class="item-option" data-value="8">XYZ</span> <span class="item-option" data-value="11">LMN</span> <span class="item-option a ...

What is the best way to trigger a re-render of a Vue component after a change in Vuex

I'm interested in developing a custom component to modify the basemap of a leaflet map without relying on L.control.layers. To achieve this, I created a sidebar component that offers options to switch between different basemaps. In my implementation, ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

Is it advisable to store JSON data in data params instead of making an AJAX call?

Previously, I stored my component data within the element's data parameter. Should I continue doing this or switch to using an Ajax call to fetch the data? 1. Using data parameter: <a href="#" data-core="{JSON-data}" id="item-1"> <a href ...

Conceal the scrollbar while navigating within the parent container

I'm currently working on implementing a parallax header on my WordPress site using the Divi theme. Below is the code I have so far: <div class="parallax"> <div class="parralax__layer parallax__layer--back"> <img src="https://crisp ...