Creating a Multilevel Dropdown Menu: A Step-by-Step Guide

I am curious about how to create a multilevel dropdown menu using Bootstrap 5 and vanilla JavaScript. I created an example based on the Bootstrap 5 dropdowns component documentation, but it did not display when I clicked on it.

The issue seems to be related to vanilla JavaScript. If anyone has any idea on how to achieve that, I would appreciate it!

Here is my code:

var myDropdown = document.getElementById('myDropdown')
myDropdown.addEventListener('show.bs.dropdown', function () {})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Bootstrap 5</title>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2d20203b3c3b3d2e3f0f7a617f617f622d2a3b2e7c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2e2323383f383e2d3c61252f23223f0c7d6278627c">[email protected]</a>/font/bootstrap-icons.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
</head>

<body>
  <div class="container py-5">
    <h1 class="mb-4">Multilevel Dropdowns With Button :</h1>
    <div class="dropdown">
      <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
                        Multilevel Dropdown link
                    </a>
      <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li class="dropdown dropend">
          <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Multilevel Action 1</a>
          <ul class="dropdown-menu" aria-labelledby="multilevelDropdownMenu1">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li class="dropdown dropend">
              <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Multilevel Action 2</a>
              <ul class="dropdown-menu" aria-labelledby="multilevelDropdownMenu2">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
        <li><a class="dropdown-item" href="#">Something else here</a></li>
      </ul>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2240404c475d6b4d4a4a444d0850544946504d1c5d42464a4a417d4a5e5c5f29">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>

Live Example

Answer №1

I modified the code to include an event listener for each dropdown-toggle to control the display of submenus. By using the 'mouseover' event instead of 'click', the submenus can be shown or hidden. Here's an example:

var myDropdown = document.getElementsByClassName('dropdown-toggle')
for (i=0; i<myDropdown.length; i++) {
    myDropdown[i].addEventListener('mouseover', function () {
        var el = this.nextElementSibling;
        el.style.display = el.style.display == 'block' ? 'none' : 'block';
    });
}
<!DOCTYPE html>
<html lang="en">

    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <title>Bootstrap 5</title>
      <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761419190205020417063643584658465b1413021745">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
      <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d0ddddc6c1c6c0d3c29fdbd1dddcc1f2839c869c82">[email protected]</a>/font/bootstrap-icons.css" rel="stylesheet" />
      <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet" />
    </head>

    <body>
      <div class="container py-5">
        <h1 class="mb-4">Multilevel Dropdowns With Button :</h1>
        <div class="dropdown">
          <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
                            Multilevel Dropdown link
                        </a>
          <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li class="dropdown dropend">
              <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Multilevel Action 1</a>
              <ul class="dropdown-menu" aria-labelledby="multilevelDropdownMenu1">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li class="dropdown dropend">
                  <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Multilevel Action 2</a>
                  <ul class="dropdown-menu" aria-labelledby="multilevelDropdownMenu2">
                    <li><a class="dropdown-item" href="#">Action</a></li>
                    <li><a class="dropdown-item" href="#">Another action</a></li>
                    <li><a class="dropdown-item" href="#">Something else here</a></li>
                  </ul>
                </li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </div>
      </div>

    </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

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Issue in Chrome where hover state does not persist after clicking, occurring sporadically

It's surprising that I couldn't find any information about this on Google. This bug is really annoying, and I'm not sure if it can be fixed without an update from Google for their browser. Description of the issue: When clicking on an eleme ...

In the Bootstrap Grid system, all posts are aligned to the left side

I have created a gallery with Bootstrap in React.js. The posts are currently displayed using the bootstrap grid system, however, all posts appear on the left side and I am struggling to center them. Any ideas on how to achieve this? https://i.sstatic.net/ ...

Creating a structured file hierarchy by extracting files from Amazon S3 and transferring them for storage in Firebase

I am looking to retrieve key/value pairs from Amazon S3 and then store some of the obtained information in Firebase to build a file system in AngularJS. This question focuses only on storing in Firebase. It is essential to be able to create an unlimited ...

Is it possible to utilize a library from one repository and integrate it into a different repository's web application through Webpack?

I have a collection of Vue.js components in a library, and I also have a Vue web application that imports these components. Both are using Webpack and are stored in separate repositories. Prior to utilizing webpack, I was using browserify-hmr and could ea ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

Encountered a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

Installing Yarn causes the download of an unconventional directory

Currently, I am facing an issue while trying to install yarn on my Macbook Pro (2017). The installation process seems to be downloading a folder called /react-praktis/ instead of completing successfully. Below is a screenshot for reference: https://i.stac ...

What are some ways to customize the appearance of VueJS components?

I am new to Vue, so I apologize if this question seems silly or if I have overlooked something. I believed that you could target a custom element like this: my-element { styles go here} However, when I created an element, it appears that I can only targe ...

Solving the Issue of Multiple Object Handling in JavaScript

Is there a way to remove the object from a JSON response and only keep the array of objects? I've tried using methods like Slice, Replace, and Filter but haven't been successful. {"error":"no data"}[{"name":"Ali"},{"name":"Momin"}] What I need ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Using the Proper 'this' Reference Without Repeating 'this' in Nested Functions

I am facing an issue in my class where I have multiple methods and properties. One of these methods contains a setTimeout() function as follows: function myClass() { this.some_property = "test"; this.PrintOnTimeout = function() { // I thou ...

Solution for tables extending beyond the navbar and footer issue

My table is extending beyond the width of both the navbar and footer. Is there a way, using HTML and CSS, to make the navbar and footer expand in width to match that of the table? Most solutions I've found focus on formatting the table instead of addr ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

Discovering hidden files within appsettings.json in ASP.NET Core 6 using Program.cs

Within Appsettings.json, the code resembles the following: { "Project": { "ConnectionString": "Data Source=(local)\SQLSERVER; Database=MyCompany; Persist Security Info=false; User ID='sa'; Password='sa ...

Can you assist me with setting a value in an ASP dropdownlist?

I have an asp dropdownlist and I need to set its value from the client side. Although I am able to retrieve the data from the client side, I am facing difficulty in setting it in my asp dropdownlist using JavaScript. HTML <div class="col-md-6 form-gro ...

Retrieving data and selecting tables using jQuery

Currently, I have an HTML table displaying various available times for scheduling purposes. My goal is to allow users to click on a specific time slot and retrieve both the column header (staff person's name) and the value of that cell (the time). Aft ...

Concealing the text input cursor (caret) from peeking through overlaid elements on Internet Explorer

Currently, I am facing an issue with a form that includes a unique widget. This particular widget automatically populates a text input when it is in focus. The problem arises when the widget appears above the text input as intended. In Internet Explorer ...

Serving files from a Node.js server and allowing users to download them in their browser

I am facing an issue with my file repository. When I access it through the browser, the file automatically downloads, which is fine. However, I want to make a request to my server and then serve the file result in the browser. Below is an example of the GE ...