Tips for automatically closing submenus in a dropdown menu using Bootstrap 4

I am trying to figure out how to make sure that when I close my dropdown menu, the submenu within it also closes. Currently, the submenu remains open if I toggle the dropdown menu again.

Visit this link for reference

Here is the HTML code snippet:

    <nav id="sideNavBar">
      <ul class="nav nav-pills nav-stacked">
        <li class="dropdown">
          <a href="#" id="menu" data-toggle="dropdown" class="droptown-toggle">Dropdown<span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li class="dropdown-submenu">
              <a href="#" class="test" data-toggle="dropdown">Submenu-1<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li>
                  <a href="#">Item-1</a>
                </li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
    </nav>

And here is the JavaScript code snippet:

  $(document).ready(function() {
    var $links = $('.dropdown-submenu a.test').on("click", function(e) {
      var submenu = $(this).next();
        $subs.not(submenu).hide()
        submenu.toggle();
      //$(this).next('ul').toggle();
      e.stopPropagation();
      e.preventDefault();
    });
    var $subs = $links.next();

  });

Answer №1

Here is a possible solution to the issue at hand:

$('.dropdown-toggle').on('click', function(e) {
  $('.dropdown-submenu .dropdown-menu').hide();
});

Note: It seems like there may be a typo in the class name droptown-toggle, but I have used it as provided.

Answer №2

Here is the code snippet for you to try out. Please disregard any 'Script error.' messages, as it's just a bug in the snippet and not related to the functionality of the code.

$(document).ready(function() {
    var $links = $('.dropdown-submenu a.test').on("click", function(e) {
      var submenu = $(this).next();
        $subs.not(submenu).hide();

        submenu.toggle();
      //$(this).next('ul').toggle();
      e.stopPropagation();
      e.preventDefault();
    });
    var $subs = $links.next();

    $('.dropdown-toggle').on('click', function(e) {
      $('.dropdown-submenu .dropdown-menu').hide();
    });

  });
<!DOCTYPE html>
<html>
<head>
  <link data-require="bootstrap-css" data-semver="4.0.0-alpha.4" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" />
  <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
  <style>
    body {
      padding-top: 60px;
    }
    
    .dropdown-submenu {
      position: relative;
    }
    
    .dropdown-submenu .dropdown-menu {
      top: 0;
      left: 100%;
      margin-top: -1px;
    }
    
    @media (max-width: 979px) {
      /* Remove any padding from the body */
      body {
        padding-top: 0;
      }
    }
  </style>

  <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script data-require="bootstrap" data-semver="4.0.5" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>

</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-md-2">
        <nav id="sideNavBar">
          <ul class="nav nav-pills nav-stacked">


            <li class="dropdown">
              <a href="#" id="menu" data-toggle="dropdown" class="dropdown-toggle">Dropdown<span class="caret"></span></a>
              <ul class="dropdown-menu">

                <li class="dropdown-submenu">
                  <a href="#" class="test" data-toggle="dropdown">Submenu-1<span class="caret"></span></a>
                  <ul class="dropdown-menu">
                    <li>
                      <a href="#">Item-1</a>
                    </li>
                    <li>
                      <a href="#">Item-2</a>
                    </li>
                    <li>
                      <a href="#">Item-3</a>
                    </li>
                  </ul>

                </li>
                <li class="dropdown-submenu">
                  <a href="#" class="test" data-toggle="dropdown">Submenu-2<span class="caret"></span></a>
                  <ul class="dropdown-menu">
                    <li>
                      <a href="#">Item-1</a>
                    </li>
                    <li>
                      <a href="#">Item-2</a>
                    </li>
                    <li>
                      <a href="#">Item-3</a>
                    </li>
                  </ul>

                </li>
              </ul>
            </li>
          </ul>
        </nav>
      </div>
    </div>
    <div class="container">
      
    </div>
  </div>
    <!-- /container -->

</body>


</html>

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

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

CDK virtual scroll problem occurs when scrolling down, items are displayed slowly and occasionally blank for a few seconds

In my project, I am utilizing Angular's virtual scroll feature. However, whenever I scroll down, the items load but flicker momentarily. I have attempted to use maxBufferPx and minBufferPx as well as adjusting positions to resolve this issue, but so ...

When viewing HTML "Div" on smaller screens, the full height may not be displayed properly

My setup includes two monitors: one is 24" and the other is my laptop's 12.5" screen. I have a red box (div) in my web application that displays full height on the larger monitor, but only partially on the smaller one. I'm puzzled as to why it s ...

Update various attributes of a div element using JavaScript

I have a progress bar in Bootstrap that receives data through a JavaScript function. Check out the progress bar below: <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...

Best practices for managing the code

How can I properly manipulate the jquery code using the var keyword? And how can I effectively use it as a parameter in @url.action? I attempted to url: '@Url.Action("CreateDisease", "DiseaseLists", new {'"+diseaseID+"', '"+ assessmen ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...

Difficulty with the increment of my counter when using addeventlistener

I'm currently facing a challenge that I can't seem to figure out... Here is the issue (in JavaScript): export default { name: "TodoList", data() { return { title: "", content: null, isDone: true, count: 0, n ...

Switching camera view on mouse click with three.js

I am new to three.js and apologize if my question is a bit complex. I have set up my scene in three.js but now I want the camera's position to smoothly transition from point A to point B (which I will specify in my code). I plan on using Tween.js to ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

The current height of the div is not meeting the desired specifications outlined in

I am encountering some issues with nested 'div' elements. Within a parent div, I have two child 'div's. <div class="case-study-video-container"> <div class="video-holder"> <?php putRevSlider( '' ); ?> ...

Enhance the password security by implementing hashing in a Flask application for the

Currently enrolled in a course on web programming with Python, I have been introduced to the Flask web framework. For my project, I have developed an application using Flask, complete with a signup form and login form that is functional thanks to SqlAlchem ...

Implementing the Google Maps API into a React application to generate a customized route between two specified points

I'm currently developing a React application that is designed to display the distance between two points on a map. Although I successfully implemented this feature using JavaScript and HTML, I am facing challenges in converting it to React as I am re ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: https://i.sstatic.net/Sru8R.png Here's the code snippet: import React, { useState } from &a ...

Issue: Unable to utilize import statement outside a module as per the guidelines of the vue-test-utils official tutorial

I'm struggling to get Vue testing set up with vue-test-utils and jest. I followed the installation guide at https://vue-test-utils.vuejs.org/installation/#semantic-versioning, but can't seem to figure out what's wrong. Here's what I&apo ...

Utilize the object's ID to filter and display data based on specified criteria

I retrieved an array of objects from a database and am seeking to narrow down the results based on specific criteria. For instance, I want to display results only if a user's id matches the page's correct id. TS - async getResultsForId() { ...

Is it possible to place a list/accordion above a button in Semantic UI?

Check out this rough code sandbox here There seems to be an issue with the accordion overflowing behind the button on the left side. I attempted to add style={{position: 'absolute', bottom:'2%', overflow: 'scroll'}} to the A ...

Cease execution of the jQuery function after a specific duration of time

Is there a way to modify this script on my website that displays an image from my webcam? Currently, the image refreshes every 5 seconds, but I want it to stop after 30 seconds to avoid using too much bandwidth. Any suggestions on how I can achieve this? ...

Incorporating click functionality in React for a to-do list feature

I've recently developed a task management application using React. However, I've encountered a couple of issues with the functionality. I am unable to mark tasks as completed by simply clicking on them, and the option to clear completed tasks by ...

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...