Hide the burger menu when a link is clicked

Is there a way to make my Bootstrap burger menu automatically close when the user clicks on a menu link, rather than having to click on the burger itself? I've tried using some JavaScript code but it ends up disabling the burger menu entirely. Can anyone provide guidance or a solution to this issue? Thank you in advance!

Javascript

var els = document.querySelectorAll('nav-link');

for( var i=els.length; i--; ) {
  els[i].addEventListener( 'click', function(){
    
     document.getElementById('navbarResponsive').style.display = 'none';
  );
}

Html

<nav class="navbar navbar-expand-lg navbar-light bg-white p-2" id="navbar">
   <div class="container">
     <a href=""><img class="logo" src="images/logo.png" alt="logo"></a>
     <a class="navbar-brand" href="#"></a>
     <button class="navbar-toggler " type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive"
       aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
     </button>
     <div class="collapse navbar-collapse" id="navbarResponsive">
       <ul class="navbar-nav ms-auto">
         <li class="nav-item active rounded-circle">
           <a class="nav-link" id="links" href="#accueil">Accueil</a>
         </li>
         <li class="nav-item rounded-circle" onclick="changeHref('#');">
           <a class="nav-link" id="links" href="#mes-services">Services</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#mes-competences">Compétences</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#mes-projets">Projets</a>

         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#tarifs">Tarifs</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#a-propos">A propos</a>
         </li>
         <li class="nav-item contact-icone rounded-circle">
           <a class="nav-link" href="#contact">Contact</a>
         </li>
       </ul>
     </div>
   </div>
 </nav>

Answer №1

Why not give this a shot:

document.querySelectorAll('.nav-link').forEach(link => {
            link.addEventListener('click', () => {
                const navbarResponsive = document.getElementById('navbarResponsive');
                if (navbarResponsive.classList.contains('show')) {                        
                    const navbarToggler = document.querySelector('.navbar-toggler');
                    navbarToggler.click(); 
                }
            });
        });
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0904041f181f190a1b2b5e4558455b">[email protected]</a>/dist/css/bootstrap.min.css">
<nav class="navbar navbar-expand-lg navbar-light bg-white p-2" id="navbar">
   <div class="container">
     <a href=""><img class="logo" src="images/logo.png" alt="logo"></a>
     <a class="navbar-brand" href="#"></a>
     <button class="navbar-toggler " type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive"
       aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
     </button>
     <div class="collapse navbar-collapse" id="navbarResponsive">
       <ul class="navbar-nav ms-auto">
         <li class="nav-item active rounded-circle">
           <a class="nav-link" id="links" href="#accueil">Accueil</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" id="links" href="#mes-services">Services</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#mes-competences">Compétences</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#mes-projets">Projets</a>

         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#tarifs">Tarifs</a>
         </li>
         <li class="nav-item rounded-circle">
           <a class="nav-link" href="#a-propos">A propos</a>
         </li>
         <li class="nav-item contact-icone rounded-circle">
           <a class="nav-link" href="#contact">Contact</a>
         </li>
       </ul>
     </div>
   </div>
 </nav>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e0ededf6f1f6f0e3f2c2b7acb1acb2">[email protected]</a>/dist/js/bootstrap.min.js" defer></script>

Answer №2

A small mistake was made in the use of querySelectorAll, but I have corrected it. Please test the updated code below to resolve the issue:

    const elements = document.querySelectorAll('.nav-link');

   

    elements.forEach(item => item.addEventListener("click", ()=>{
        document.getElementById('navbarResponsive').style.display = 'none';
    }))

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

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

"Encountered a syntax error while attempting to reference an attribute on an empty object

> "[object Number]" === Object.prototype.toString.call(1) // #1 < true > "[object Number]" === {}.toString.call(1) // #2 < true > {}.toString.call(1) === "[object Number]" // #3 < SyntaxError: Unexpected token ...

Invoke a Google Apps Script through AJAX that necessitates authentication

I am looking to access a Google Apps Script via AJAX that requires user authorization to send an email from their Gmail account. The challenge lies in the fact that I need to send the email from within the Google Apps Script. The call originates from my w ...

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

What is the best way to instruct jQuery to disregard an empty server response?

After examining this piece of code: $.ajax({ type: "POST", url: theRightUrl, data: whatToPost, logFunction: whatever, suppressSuccessLogging: !0, dataType: "html" }); I encountered an issue where Firefox displays a "no element ...

After making 5 Ajax get requests, there is no response being received

Currently, I'm facing an issue when trying to retrieve information from the MongoDB server to the frontend using an AJAX GET request. Everything works smoothly until I attempt to call the JavaScript function multiple times. Strangely, if I call the fu ...

"Hey, do you need a see-through background for your

Currently, I am implementing the JS library found at . Unfortunately, I am struggling to make the background transparent or any other color. It appears that the issue lies in the fact that the tab styles are being overridden by the JS library whenever the ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Halt hovering effect after a set duration using CSS or Vanilla JavaScript

Looking for a way to create a hover effect that lasts for a specific duration before stopping. I want the background to appear for just 1 second, even if the mouse remains hovering. Preferably using CSS or JavaScript only, without jQuery. To see my curren ...

Converting Greek text to UTF-8 using Javascript

Currently, I am working on a project with my teacher to digitalize a Greek textbook by transforming it into an online application. This process involves the conversion of a Shapefile, which draws polygons on maps along with polygon descriptions, and mappin ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

How can I show a "buffering" message in jPlayer?

I need assistance with jPlayer. Here is the code I am using: $("#jquery_jplayer_1").jPlayer({ ready: function () { $(this).jPlayer("setMedia", { title: "Alin", artist: "song", mp3: "utl" ...

For my Bootstrap website, it's a constant struggle to balance between having a responsive menu item and ensuring its correct visual appearance

I need help with creating a unique menu design for my website. On the desktop site, I want to display "username/password/sign in" buttons, while on the mobile responsive version I only want to show a single "sign in" option that redirects users to the sign ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...