`Trouble with collapsing Bootstrap 4.1 navigation bar`

During the recent updates made to these websites, I made some changes to the menu behavior so that it collapses on mobile devices when a menu item is clicked. For the most part, it works smoothly, but there is one issue. When I click on a mobile menu with sub-items for the first time, it expands briefly and then collapses. Subsequent attempts work fine. I have provided a video for better understanding.

Below is the javascript code that I included:

$( document ).ready( function () {

    $('.navbar-nav>li').on('click', function(){
        $('.navbar-collapse').collapse('hide');
    });

} );

Answer №1

After much thought, I have devised a solution that may still have room for improvement.

$( document ).ready( function () {
  $('.navbar-nav>li').on('click', function(){
      let $navbarNavLiElement = $( this );
      let $parentElement = $navbarNavLiElement.parent();

      if ($navbarNavLiElement.hasClass("nav-item dropdown") && !$navbarNavLiElement.hasClass("show")) {
        $('.navbar-collapse').collapse('show');
      } else {
          if ($navbarNavLiElement.hasClass("dropdown-togle")) {
            $('.navbar-collapse').collapse('show');
          } else {
            $('.navbar-collapse').collapse('hide');
          }
      }
  });
});

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

Place additional text above the export button within Highcharts

Presently, I'm utilizing the Highcharts API here and here to customize the export button for Highcharts. I am attempting to position an ellipsis inside the export button in order to adhere to certain style guidelines. However, due to the limitations o ...

When attempting to execute the "npm run start" command in a ReactJS environment, an error message appeared

'react-scripts' command is not being recognized as a valid internal or external command, able to use program or batch file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] start: react-scripts start npm ERR! Ex ...

Experiencing difficulties accessing Facebook using ngFacebook on angularjs application

I've been working on implementing ngFacebook login into my Angular app, but I'm facing an issue with logging in to Facebook. Even after calling '$facebook.log()', nothing is being displayed in the console. This is a snippet of my Angul ...

Verification of user input upon clicking the submit button within a form

I am encountering an issue with validating my form, as no errors are displayed in the console. I have followed the instructions provided by Bootstrap documentation but to no avail. My aim is to implement a feature where clicking on the button triggers an a ...

Use ngResource's $delete method to remove a record from a query object

Just starting out with angular and trying to work with the $resource library for API services. I'm having trouble figuring out how to delete a record obtained through the query() method. Specifically, we have an endpoint for user notifications. The go ...

Is it possible for the code to display the value from the previous refresh rather than the most recent value added?

In my project, there is a functionality where a column of buttons in a table triggers a script to read the data associated with the clicked button and send it to another PHP file: <!-- Script that retrieves lecturer details for SHOW functionality - ...

Creating a custom event handler for form input changes using React hooks

A unique React hook was created specifically for managing form elements. This hook provides access to the current state of form fields and a factory for generating change handlers. While it works seamlessly with text inputs, there is a need to modify the c ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

What could be the reason for Vue model not updating with input.val(value) changes?

I've created an editable table: <div id="myTable"> <b-table class="overflow-auto" :items="filtered" :fields="visibleFields" :filter="filter"> <template v-for="field in ed ...

Switch up your code and toggle a class on or off for all elements that share a specific class

I've been attempting to create a functionality where, upon clicking a switch, a specific class gets added to every element that is assigned the class "ChangeColors". Unfortunately, I have encountered some difficulties in achieving this task. The error ...

Is it possible to save round items within a session?

While utilizing Blocktrail's API for bitcoin wallet management, I encountered an issue with circular references within the returned wallet object. The goal is to store the decrypted wallet in the user's session to avoid password re-entry. Howeve ...

ERROR702: The requested action cannot be completed as the object does not have support for the specified property or method 'attr'

An error occurred while trying to execute the following code... The code snippet provided is for creating a vertical bar chart using D3. However, when executed, it results in an error and the chart is not displayed as expected. // Data for ...

Create a customizable JavaScript clock that synchronizes with an image to display the current hour, minute

I am having trouble with my clock not working I have created images for the hour, minute, second, and AM/PM https://i.sstatic.net/4zg00.png I attempted to use this code: <script language="JavaScript1.1"> <!-- /* Live image clock III Written b ...

How to close a JavaScript popup with Selenium automation

I am currently working on a Python project that involves using Selenium to extract information from Hemnet website related to my area. However, I am encountering a problem with a popup that appears when I open the page through Selenium. I have attempted va ...

Execute document.write and open within the current window

I'm encountering an issue while trying to write to a document: NewWindow.document.write("Hi, this is test"); NewWindow = window.open("pages/Example.html","_self"); However, the page appears blank. If I use NewWindow.document.write("Hi, this is test ...

Using a contenteditable div with a set maximum character limit, powered by jQuery

Here is the challenge at hand - I am looking to restrict input to no more than N characters in a contenteditable div using either native JS or JQuery. For example, if a user inputs 10 symbols, they should not be able to input any more and can only clear ...

unable to determine the reason for the undefined value

My function is designed to remove an element tag when it's clicked on and also remove the corresponding content/ingredient from another list. Everything seems to work fine in the browser, but when I check the console, a TypeError pops up, and I can&ap ...

The desired result is not appearing when using a `fetch` request, but it does show up with an

I am facing an issue with two different requests - one using ajax and the other using fetch, its successor. When I send my data using fetch to the same API as ajax, I notice that the results are not consistent. Ajax $.post(this.config.baseUrl + this ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Tips on effectively recycling a buffer in JavaScript

After running this code, the application crashes due to memory issues: var buf; console.log(process.memoryUsage()) for(i=0; i<10000000; i++){ buf = Buffer.alloc(1024) buf.clear delete buf buf = null } console.log(process.memoryUsage()) ...