Close the Bootstrap burger menu after clicking on a scrollspy link

Is there a way to automatically collapse the Bootstrap burger menu when clicking on a scrollspy link?

While browsing my website on a mobile device, the Bootstrap navigation menu switches to a burger icon. However, when you click on an internal link that leads to a specific section on my index.html (like #aboutMe), the navigation menu remains open. I want it to collapse automatically after clicking on the link.

You can find the code on: https://github.com/senkvalentin/personal_page or visit the website at:

Here is the relevant snippet of my HTML:

.h-100vh{
  height:100vh;
}
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d8d8c3c4c3c5d6c7f78299879985">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcded3d3c8cfc8ceddccfc89928c928e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<div data-spy="scroll" data-target=".navbar" data-offset="50">
  <div class="container">
    <div class="row">
      <nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
          <a class="navbar-brand" href="/"><img src="./img/logo.png" alt="">
          </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 mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="#home">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#aboutMe">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
              </li>
              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                      Admin
                    </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                  <li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    </div>
    <div id="home" class="h-100vh bg-warning">Home</div> 
    <div id="aboutMe" class="h-100vh bg-success">About Me</div>
    <div id="projectsList" class="h-100vh bg-primary">Project</div>

I have already checked out: How to hide collapsible Bootstrap navbar on click
And: Bootstrap panel-collapse collapses when you click on a link inside it is clicked

but none of the solutions worked for me.

I am using the latest versions of jQuery and Bootstrap (5.0.1):

<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88eae7e7fcfbfcfae9f8c8bda6b8a6b9">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

Answer №1

By using Jquery, you can easily simulate a click on the navbar-toggler button when a link is clicked:

$('.nav-link').click(function(){
  $('.navbar-toggler').click();
});

$('.nav-link').click(function(){
  $('.navbar-toggler').click();
});
.h-100vh{
  height:100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34565b5b40474046554474011a041a06">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="593b36362d2a2d2b3829196c7769776b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<div data-spy="scroll" data-target=".navbar" data-offset="50">
  <div class="container">
    <div class="row">
      <nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
          <a class="navbar-brand" href="/"><img src="./img/logo.png" alt="">
          </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 mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="#home">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#aboutMe">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
              </li>
              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  Admin
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                  <li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    </div>
    <div id="home" class="h-100vh bg-warning">Home</div>
    <div id="aboutMe" class="h-100vh bg-success">About Me</div>
    <div id="projectsList" class="h-100vh bg-primary">Project</div>

Answer №2

Start by selecting all elements with the class .nav-link except for those with the class .dropdown-toggle.
Next, add an event listener to toggle the visibility of the .navbar-collapse when clicked:

$(document).ready(() => {
  let $navlinks = $('.nav-link').not('.dropdown-toggle');
  // console.log($navlinks)
  $navlinks.click((e) => {
    $(e.target).closest('.navbar').find('.navbar-collapse').collapse('toggle')
  })
})
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5c51514a4d4a4c5f4e7e0b100e100f">[email protected]</a>/dist/css/bootstrap.css">

<div data-spy="scroll" data-target=".navbar" data-offset="50">
  <div class="container">
    <div class="row">
      <nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
        <div class="container-fluid">
          <a class="navbar-brand" href="/"><img src="./img/logo.png" alt="logo">
          </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 mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="/">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#aboutMe">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
              </li>
              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  Admin
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                  <li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
                  <li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </nav>
    </div>

    <script src="https://code.jquery.com/jquery-latest.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45272a2a31363137243505706b756b74">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

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

Validating textfields and dropdowns for dynamic HTML identifiers using jQuery

I am attempting to validate a dropdown and text field together. Both fields can either be left empty or both must be filled. The HTML ids are generated dynamically. I have tried the code below but it is not working as expected. Here are the resources I use ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...

Having trouble accessing a DOM element within a Vue component while using vanilla JavaScript

I am attempting to dynamically update data from a Vue component using jQuery in a Webpack project. Below is the code snippet: <template> <div id="container"> <slot>show string!!</slot> <div id="s_container"&g ...

Error: Unrecognized controller in AngularJS/Ruby on Rails framework

I've been working through the tutorial on implementing an Angular JS / Ruby on Rails app from Thinkster and have encountered a problem. Despite my controllers being listed in the page's sources when inspecting the content, they are not being rec ...

With *ngFor in Angular, radio buttons are designed so that only one can be selected

My goal is to create a questionnaire form with various questions and multiple choice options using radio buttons. All the questions and options are stored in a json file. To display these questions and options, I am utilizing nested ngFor loops to differ ...

Using Jquery for HTTP requests in PHP

I am currently working on enhancing an auto-complete module for jQuery. After the text field is auto-completed, I move to the next field (a drop down). Once that drop down is focused, I want to compare it against the text field and dynamically populate the ...

Can a JavaScript or jQuery function be triggered on input change to perform a PHP call to check a database?

Is it possible to implement live form validation without a page reload? I am looking to add a function like the one below: <input onchange="validate();"></input> function validate() { // PHP here to check input value against table value o ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

ReactJS presents an issue where buttons on the navigation bar are not properly aligned

I am currently utilizing the navbar component from Bootstrap 5, and I've encountered a UI problem. What is my current setup? This is the existing structure of my navbar: https://i.sstatic.net/eETzd.png What is my desired outcome? I aim to have the n ...

Guide to creating the onclick feature for a dynamic button in Meteor

<template name="actionTemplate"> {{#each action}} <button class="myButton" id={{_id}}>btn</button> {{> action}} {{/each}} </template> <template name="action"> <div class="sct" id={{_id}}> ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page. The code in my index.js file looks like this: app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dir ...

Creating separate Vuex stores for dynamic components

This question really had me stumped for a while. I couldn't find the answer here (asking around didn't help either). However, after conducting some research and seeking advice from various sources, I believe I have finally arrived at a solution t ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

The JSON.Parse function in Google Apps Script is leading to a 'server connection error' message during debugging

I'm not a professional developer, but I do code occasionally. Currently, I am working on some Apps Script code to interact with an API and store the data in SQL. Most of it is working fine, but I have encountered an issue while debugging in the Apps S ...

A step-by-step guide to displaying API data in a React frontend using functional components

I've managed to create a backend API using Node+Express+MSSQL and tested the routes with POSTMAN. However, I'm facing challenges when trying to display the data on the front-end using React Functional components/hooks. I'm unsure if I'm ...

What is the process for transforming a string into a dictionary using jinja2?

I have a variable called {{data}} which contains a string formatted like this: *{"a": "1", "b": "2", "c": 3, "d": 4}* My goal is to access the values in this format: *{{data.a}} --> 1 {{data.b ...

What is the best way to link my PHP with MySQL in order to execute an AJAX query?

I am currently working on making this page sortable using a dropdown selection menu. At the moment, there are only two different car makes displayed and they are not sorting properly. My ultimate goal is to enable sorting by make, model, and year, but I ne ...

Store a JSON object without creating a reference to it

My issue is presented in a much simpler manner. Here is the json (you can view it here if you wish) {"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303 ...