DEV Community

Cedric Muuo
Cedric Muuo

Posted on

How to create a dropdown menu on hover using jQuery

Hello fellas, in today's post I want to show you guys a cool jQuery trick I learned recently.

When you are creating interactive web pages it is very likely you will need to have a navigation bar that has buttons or links which direct users to other webpages. In some scenarios, you need to display a couple of options for the user to choose from and an easy to use choice for this would be using a bit of jQuery to show a dropdown menu with links on hover.

For this you will need to have jQuery installed at the base of your project and linked to your HTML file as so;

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

Ok so let's hop right into adding the flesh of the project. First, let us create a wrapper that will hold all of our content. Then create a button or just a link that will drop down our options.

<div class="wrapper">
<div class="button">
<button value="Hover on me!" id="hover">Hover On Me!
</button>
</div>

The next step is to add the list of options you want to be displayed on hover. In this case, we will create links to other pages.

<div class="dropdown">
<ul>
<li><a href="#">JavaScript Page</a></li>
<li><a href="#">HTML Page</a></li>
<li><a href="#">CSS Page</li></a>
</ul>
</div>
</div>

Now we have our HTML all set up. The next step is to set the display of the dropdown options to 'none'. This is because we only want this list of options to appear when we hover over the button and disappear when the mouse moves away.

In your CSS file;

.dropdown{
display: none;
}

Looking pretty great so far, so let us proceed to the final step and this will be creating the actual hover effect using JavaScript.

In your JS file add these five lines of code;

$(document).ready(function(){
$(".button").hover(function(){
$(".dropdown").slideToggle();
});
});

What we are simply telling jQuery here is:

  1. Check if the document is done loading using .ready()
  2. 'Listen' to the element with the class "button" and check if the user hovers on it using .hover()
  3. If the user hovers on the element, slide down the dropdown menu using slideToggle()

Note: "slideToggle()" toggles between "slideDown()" and "slideUp()" depending on the element method which in this case is "hover()", hence the dropdown menu will slide down when the user hovers above the button and slide up when the user moves away from the button.

Happy coding and feel free to leave comments down below

Top comments (1)

Collapse
 
goodjob profile image
GoodJob

Huge problem when mouse is hovered on sub-menu - it dissapears...