Bootstrap: nav-link remains visible even after a dropdown-item is chosen

I am aiming to accomplish the following - when a dropdown-item from the navbar is selected, I want to execute BOTH of the following actions:

  • Scroll to the div with the specified target id
  • Collapse the navbar back to its initial state (fully rolled up, hidden)

So far, I have only been able to achieve one of the above actions at a time. Can anyone offer guidance on how I can accomplish both tasks simultaneously? I believe the first dropdown-item anchor should handle this, but for some reason, it fails to scroll to the targetId after collapsing the navbar. When I remove data-toggle="collapse" and

data-target=".navbar-collapse.show"
as shown in the second anchor, the anchor successfully scrolls to the target but the navbar does not collapse.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<nav class="navbar navbar-dark bg-dark fixed-top">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

  <div class="collapse navbar-collapse" id="navbarsExampleDefault">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Menu</a>
        <div class="dropdown-menu shadow rounded" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="#targetId" data-toggle="collapse" data-target=".navbar-collapse.show">The nav-link hides, but doesn't scroll to the target</a>
          <a class="dropdown-item" href="#targetId">Scrolls to the target, but the nav-link doesn't hide</a>
        </div>
      </li>
    </ul>
  </div>
</nav>
<!-- navbar ends here -->
<div id="targetId">Content</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2928d92928790cc8891a2d3ccd3d4ccd2">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

Thank you for your assistance!

Answer №1

To achieve this, you can utilize Javascript.

document.querySelectorAll('.custom_collapse').forEach(cur => {
  cur.addEventListener('click', () => {
    document.querySelector('.navbar_collapse').classList.remove('show');
  });
});
#targetId {
    /* Adjust to target */
    margin-top: 120vh;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

<nav class="navbar navbar-dark bg-dark fixed-top">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

  <div class="collapse navbar-collapse navbar_collapse" id="navbarsExampleDefault">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Menu</a>
        <div class="dropdown-menu shadow rounded" aria-labelledby="dropdown01">
          <a class="dropdown-item custom_collapse" href="#targetId">The nav-link is hidden, but doesn't hit the target</a>
          <a class="dropdown-item custom_collapse" href="#targetId">Hits the target, but the nav-link is not hidden</a>
        </div>
      </li>
    </ul>
  </div>
</nav>
<!-- Navbar section ends here -->
<div id="targetId">Content</div>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e0ffe0e0f5e2befae3d0a1bea1a6bea0">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></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

AngularJS - A pagination demonstration incorporating intelligent logic inspired by Google's approach

I struggled to implement a paging solution that I came across online. The issue seems to be related to the timing of function calls, specifically how the setPage function is triggered before all data is retrieved, causing it to not properly determine the t ...

HELP! Imagemaps are being ruined by overlapping DIVs!

I encountered a minor issue. In summary, I have a container div that displays rotating images and image maps with clickable links within each image setup like a gallery with built-in navigation. Recently, I was tasked with adding simple animations to the i ...

Assess transcluded content prior to template compilation in an AngularJS directive

I am currently developing a custom "collapseText" directive using AngularJS. The purpose of this directive is to display a specified maximum number of characters and provide a "Read More" option to expand the text if it exceeds the limit. My goal is for t ...

Iterate through a collection of objects, check their unique identifiers, and combine the objects together based on their

I am currently iterating through an array of objects in an attempt to extract the id and carId values from them. My code snippet looks like this: getIds(array) { for (var index in array) { var combinedIds = array[index]; if ...

behind the scenes of a disappearing bootstrap modal

Greetings everyone! Currently, I am deep into the process of identifying and resolving a pesky bug that has been impacting my work. The project in question involves developing a module for an open-source platform built on Laravel and Bootstrap - Microweb ...

How can CKEditor ensure that there is a paragraph tag within a div element?

Working on my current CMS, I have the need to include some custom HTML (which is functioning as expected): var element = CKEDITOR.dom.element.createFromHtml("<div class='sidebar'>Edit Sidebar Text</div>"); The issue arises when atte ...

Is object rest/spread properties not supported by Node.js version 6.3.1?

After attempting to run this code in Node.js v6.3.1 CLI, the following output was generated: let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; console.log(x); // 1 console.log(y); // 2 console.log(z); // { a: 3, b: 4 } Unexpectedly, the output was diffe ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Difference between ng-controller variable and ng-init variable

When working with the code snippet below in angularJS, <script type="text/javascript"> angular.module('app').controller('add', ['$scope',function($scope) { $scope.name = "Bonita Ln"; }]); </script& ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Cross-browser compatibility problem: Firefox not displaying layout properly

I am encountering browser problems, as well as issues when using the same browser on a different computer. The links on my website are not positioned correctly over the background. When viewing with Firefox, the opacity and positioning features are not fu ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

What is the best way to maintain scrollbars on mobile devices?

I'm currently building a cross-platform application using Angular 4 that needs to work seamlessly on both mobile and desktop devices. Is there a special trick to prevent the scrollbars from disappearing when viewing this page on a mobile browser? I&ap ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Save the HTML elements in an object and then use the ng-include directive to include the template

Currently experimenting with this code snippet: var CustomTable = function($elem) { this.properties.element = $elem; this.initialize(); }; CustomTable.prototype.PROPERTIE = { secondElement: $('.second') // this element ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Tips on saving stimulsoft report js onto a server using Angular

I am working on a report designer component and have assigned a method to the onSaveReport event. However, I am encountering an issue where the member of my component is showing as undefined. options: any; designer: any; public document: Report ...

"Implementing a where clause in an AJAX request with a date range

Here is the HTML code snippet: <div class="col-md-4 input-group input-group-lg search"> <span class="input-group-addon"><i class="fa fa-fw fa fa-calendar red"></i></span> <input id="config" class="form-control ...