How to toggle Bootstrap 5 dropdowns with both click and hover functionality

I am currently working on a dropdown menu using HTML/CSS/JavaScript/jQuery and Bootstrap 5. The objective is to have the menu open/close both when hovered over and clicked on:

  • When the mouse hovers over the dropdown element, the menu should open
  • Once the mouse leaves the dropdown element, the menu should close
  • If a list item is clicked, the menu should also close

Bootstrap naturally closes the dropdown menu when a list item is clicked, but due to the addition of hover functionality, this feature is not functioning properly. Currently, the menu only closes once the user moves the mouse outside the dropdown menu. This behavior aligns with the open/close functionality based on hover, however, I am exploring if there's a way for the menu to still close when an item is clicked.

I attempted to add a click function to toggle the opening/closing of the menu, as well as included

data-bs-auto-close="true"
to the dropdown element, but neither approach has resolved the issue.

Has anyone faced a similar situation before or found a possible solution? Refer to my code below. Please note that the hover functionality doesn't work when running the code in S/O, so the problem may not be evident here. To experience the issue, it's recommended to run the code in CODEPEN.

// Hide menu on click solution #1
$(".dropdown").on("click", () => {
  var dropdownMenu = $(this).children(".dropdown-menu");
  if (dropdownMenu.is(":visible")) {
    console.log("hide menu");
    dropdownMenu.css("display", "none");
  }
});

// Hide menu on click solution #2
$(".dropdown-menu > li").click(function() {
  console.log("hello");
  $(this).removeClass("show").attr("aria-expanded", "false");
  $(this).find(".dropdown-menu").removeClass("show");
});
// Show dropdown on mouse hover
.dropdown:hover .dropdown-menu {
  display: block;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8f8282999e999f8c9dadd8c3dcc3de">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63010c0c17101711021323564d524d50">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>


<div class="dropdown">
  <div class="deep-dive-toggle-container dropdown-toggle" type="button" id="account-toggle-container" data-bs-toggle="dropdown" data-bs-auto-close="true" aria-expanded="false">
    <div class="deep-dive-toggle-text">Account</div>
  </div>
  <ul class="dropdown-menu" aria-labelledby="accountDropdown">
    <li id="recap-dropdown-item" class="dropdown-item">Recap</li>
    <li id="account-timeline-dropdown-item" class="dropdown-item">
      Timeline
    </li>
    <li id="breakdowns-dropdown-item" class="dropdown-item">
      Breakdowns
    </li>
    <li id="search-dropdown-item" class="dropdown-item">Search</li>
    <li id="account-posts-dropdown-item" class="dropdown-item">
      Posts
    </li>
  </ul>
</div>

Answer №1

This situation really caught me off guard. I experimented with different approaches, but they all seemed to lead me towards the same outcome.

I should have known better. Through past experiences, I've learned not to try and alter Bootstrap's behavior without utilizing Bootstrap's designated methods. You can't just go in thinking, "I know jQuery, I got this," because Bootstrap has its own intricate system that will resist any changes you try to make independently.

Upon consulting Bootstrap's documentation on Dropdowns, I discovered the essential methods and events associated with manipulating Dropdowns. This reference guide provides the necessary tools for customizing Bootstrap functionalities to meet your needs.

The toggle method is particularly relevant in this scenario, as stated in the documentation as, "Toggles the dropdown menu of a given navbar or tabbed navigation."

In reality, toggle is indeed a jQuery method rather than a Bootstrap feature. However, following the documentation will steer you in the right direction when dealing with such instances. Disregarding these guidelines will only lead to frustration and difficulty (which is why I tend to avoid using Bootstrap as much as I probably should, since both Bootstrap and I have strong opinions that clash).

Below is the solution that worked for me. The hover functionality may be a bit sensitive, but adding a slight negative top margin to .dropdown-menu could potentially resolve the issue by eliminating the gap between it and the .dropdown-toggle, which could trigger a mouseout event.

The solution primarily involves JavaScript, within a markup structure and CSS enclosed in an HTML5 boilerplate, alongside imported Bootstrap and its dependencies. I relocated the solution to a JSFiddle platform, as I find Codepen to be bothersome: https://jsfiddle.net/bd1rxsn5/8/

Rethinking the approach...

It appears that the sensitivity issue I previously mentioned is more related to the button inside the toggle rather than an imaginary margin. There seems to be an inconsistency where hovering slightly beside the button and then moving over and down to the menu works reliably, but hovering directly on the button itself may not produce the expected result. Additionally, hovering to the right of the button initially opens the dropdown, but closing the dropdown requires tracing back over the button to the menu. Let me attempt to capture this behavior so you can witness what I mean...

My suggestion would be either: 1. if you insist on keeping the button, experiment with its z-index. I would recommend absolutely positioning it relative to the containing .dropdown and setting its z-index below the [transparent] dropdown, or 2. consider removing the toggle button altogether if it is not serving its intended purpose. If you prefer the visual element, utilize your browser's inspector tool to replicate the appearance with a static non-Bootstrap element like a div or similar element.

https://i.sstatic.net/WKfimawX.png

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

Chart: Observing the Discrepancy in the Initial X-Axis Points

I'm working on incorporating multiple charts onto one page, with each chart centered and stacked one after the other. I've set a fixed width for the graph canvas. The challenge arises from the varying ranges of tick values - one chart may have a ...

Updating model/schema dynamically within Express Router

My express server handles api calls by directing them to specific routes. app.use('/api/data01', require('./routes/dataRoute01')) app.use('/api/data02', require('./routes/dataRoute02')) app.use('/api/data03&apo ...

Save and showcase an array as individual objects within local storage

I am looking to input data using a specific product ID and save it locally. Upon clicking the button, the data should be stored in the local storage. It is possible for a single product to have multiple filenames associated with it. For the customer, if t ...

Images are not appearing correctly on Chrome browsers when using Windows operating system

img tags seem to have unusual margins in Chrome, Edge, and Opera browsers, while Firefox displays them correctly. Queries What is causing these margins specifically in Chrome? The Devtool does not detect any margin properties. Is there a straightforward s ...

I am looking to refresh the location of my vehicle using JavaScript

I am currently using a leaflet map that displays my location successfully. However, I want to update my location every 10 seconds without refreshing the entire page. Is there a way to achieve this without updating the whole page? Below is the code snippet ...

Storing HTML content in a MySQL database using the MVC architectural pattern

I currently have a straightforward method that successfully posts a string to my MySQL server and saves the text without any issues. However, when I include a tag within the string, my google console displays an error stating that the page could not be f ...

Electron's see-through window that can be clicked on

I'm currently facing a challenge in Electron where I am trying to create a transparent window. Despite successfully finding solutions for other issues, this particular problem has me stumped. My goal is to develop a full-size browser window in Electro ...

Prevent alert box from closing automatically without clicking the ok button in ASP.NET

I'm creating a project in ASP.NET where I need to display an alert box and then redirect to another page. Below is my code: var s = Convert.ToInt32(Session["id"].ToString()); var q = (from p in db.students where p.userid == s ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

What is the best way to assign an ID to a specific HTML element within NetSuite's Document Object Model

Attempting to utilize jQuery in NetSuite to assign a value to an element for testing purposes, but struggling to locate the HTML DOM ID of certain custom drop-down lists. It's not the internal ID. For example: <input type="text" id="soid"> Wh ...

What is the best way to dynamically generate a component and provide props to it programmatically?

I am interested in creating a function that can return a component with specific props assigned to it. Something like a reusable component for Text/View/Pressable, where styles can be extracted and passed as props. Personally, I find it more efficient to s ...

Leveraging IPFS to host a CSS stylesheet

I've been trying to load a css stylesheet using this link... I attempted adding the link tag to both the main and head tags. <link type="text/css" rel="stylesheet" href="https://ipfs.io/ipfs/Qmdun4VYeqRJtisjDxLoRMRj2aTY9sk ...

Success/Fail Page for Form Redirect

I've been struggling to figure out how to redirect my form to a success or fail page. I've scoured the internet for solutions, looking into traditional form redirects and even JavaScript onClick redirects. Can someone guide me on adding a redirec ...

I need help figuring out how to retrieve the full path of an uploaded file in JavaScript. Currently, it only returns "c:fakepath" but I need

Is there a way to obtain the complete file path of an uploaded file in javascript? Currently, it only shows c:\fakepath. The file path is being directly sent to the controller through jquery, and I need the full path for my servlet. Are there any alte ...

Using Bootstrap classes within a specified class declaration

Can you nest style classes within a single class? For example: .my-upper-class{ .hidden-md, .hidden-sm, .hidden-lg} ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

Accessing a service instance within the $rootScope.$on function in Angular

I'm looking for a way to access the service instance variable inside the $rootScope in the following code. myapp.service('myservice',function($rootScope) { this.var = false; $rootScope.$on('channel',function(e,msg) { v ...

Require help addressing the challenge of cross-domain compatibility while utilizing node.js on the server and JavaScript on the client side

I have set up an http server on port 8081 and am attempting to retrieve JSON data using the getJSON function in jQuery. However, I keep encountering cross-domain (CORS) issues. I considered using JSONP as a workaround, but I'm unsure how to implement ...

The Google Maps feature is experiencing issues with its display after the integration of a jQuery mobile panel

Ever since I added the panel div, the map on my page has been displaying incorrectly. Now, it appears cluttered at the top with a wide space below. The button in the top left corner is meant to open the panel, which it does successfully. Apologies for the ...

Disable the ability to scroll the background when the lightbox is opened

Currently incorporating Featherlight for a lightbox feature. Encountering an issue where the background remains scrollable when the lightbox is open. Typically, lightboxes require adding a class to the body with overflow:hidden; to resolve this problem. S ...