jQuery

Drop down menu (jQuery)

Last updated: 10.10.2025
Views: 263

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

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

  • How to Detect Scroll Direction on a Page Using JavaScript
    Sometimes it is necessary to detect the direction of vertical scrolling on a site, for example, to perform some actions with the footer or header. Let's write code to det...
  • jQuery Accordion Plugin
    An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I oft...
  • Smooth Scrolling to Anchor Using JavaScript
    Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smo...

Leave a Reply

Your email address will not be published. Required fields are marked *