Drop down menu (jQuery)
Last updated: 10.10.2025
Views: 415
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay in the disappearance of the drop-down elements.
Let’s consider a simple menu with one nesting level. We will write the code using jQuery. Although jQuery is not the most modern tool, this library continues to be used in many projects.
HTML
<ul class="nav">
<li>
<a href="#">Item 1</a>
<ul>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
</ul>
</li>
<li>
<a href="#">Item 2</a>
<ul>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
</ul>
</li>
<li>
<a href="#">Item 3</a>
<ul>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
<li><a href="#">Subitem</a></li>
</ul>
</li>
</ul>
JavaScript
(() => {
const itemMenu = $('.nav > li');
let close, flag;
itemMenu.on('mouseenter', function() {
if (flag === this) {
clearTimeout(close);
}
$(this).find('ul').stop().fadeIn();
});
itemMenu.on('mouseleave', function() {
close = setTimeout(() => {
$(this).find('ul').stop().fadeOut();
}, 300); //set delay 300 ms
flag = this;
});
})();
Nested menu items should be hidden using CSS
CSS
.nav li ul {
display: none;
}
You can write other necessary styles yourself depending on your design. You can see an example of how the menu might look and work on Codepen: https://codepen.io/igorrybalko/pen/XJrparJ
Similar posts:
-
Finding the Distance Between Two Points on a Map Using JavaScript (TypeScript)
If you have the coordinates of two points on a map, calculating the distance between them is a fairly straightforward task. This type of calculation is commonly used in m...
-
How to Get Max Value in JavaScript Array
A short note about finding the maximum value in a JavaScript array with numeric values. The Array object in JS does not have its own max method. To find the maximum va...
-
How to Create a Custom jQuery Plugin
The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you ...
Leave a Reply