Signup/Sign In

How to open Bootstrap dropdown menu on hover rather than click?

The Bootstrap dropdown menu opens on click by default. But we can also open the Bootstrap dropdown menu on hover.

There are no such classes to open dropdown on hover but we can do this using the CSS. We will learn to do so in this tutorial.

Using the CSS property

We can use the CSS hover property to the dropdown to add hover to the dropdown menu. When hovering on the dropdown menu, it will open the list rather than clicking on it

Example: Open dropdown on hover using CSS

Here is an example to open dropdown on hover.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Bootstrap Example</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" >
	<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" ></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js"></script>
	<style> 
        .dropdown:hover .dropdown-menu {
            display: block;
        }
	</style>
</head>
<body>
    <h2> Hover to open the dropdown </h2>
    <div class="dropdown">
	  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
		Dropdown button
	  </button>
   <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
    <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>
</div>
</body>
</html>

Output

Here is the output of the above program.

open dropdown on hover

Using JQuery

For Bootstrap 4, we can use JQuery to open dropdown on hover. Here are some functions used in JQuery.

  • .ready method is used when the program is ready and DOM is loaded.
  • .hover(function) is used to hover the dropdown.
  • .addclass(''open') is used to open the dropdown.

Example: Open dropdown using JQuery

In this example, we have used JQuery to open dropdown on hover.

Conclusion

In this tutorial, we have learned to open a dropdown menu on hover. It can be done using CSS hover properties or using JQuery for Bootstrap 4. The CSS hover properties are supported in almost all versions of bootstrap.



About the author: