Issues Found in Your Code
Main Concern
The problem arises from the immediate re-adding of the class after removal, resulting in the dropdown content never being visible.
For jQuery's .hover()
function to work properly, it requires two function arguments - one for mouse enter and another for mouse leave events.
Specific Child Element Problem
Another issue lies in how your code toggles the class on all submenus instead of targeting only the direct child of the hovered list item. To fix this, you can use:
$(this).find(".dropdown-content").first()
This modification ensures that only the desired sub-ul
is affected. Alternatively, you could also utilize .eq(0)
instead of .first()
.
Invalid HTML Structure Issue
It's crucial to observe that a ul
element should only have li
children. Therefore, any sub-ul
must be enclosed within an li
tag.
Avoiding the Use of JavaScript Solution
To address this matter without resorting to JavaScript, consider implementing CSS-only solutions:
.dropdown-content {
display: none;
}
.dropdown:hover > .dropdown-content {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="nav" class="menu-desktop">
<li><a href="#">HOME</a></li>
<li class="dropdown"><a href="#">COMPANY</a>
<ul id="submenu" class="dropdown-content">
<li><a href="#">submenu 1</a></li>
<li><a href="#">submenu 1</a></li>
<li><a href="#">submenu 1</a></li>
<li class="dropdown"><a href="#">submenu 1</a>
<ul id="submenu2" class="dropdown-content">
<li><a href="#">submenu 2</a></li>
<li><a href="#">submenu 2</a></li>
<li><a href="#">submenu 2</a></li>
<li><a href="#">submenu 2</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">CUSTOMERS</a></li>
<li><a href="#">CONTACT</a></li>
</ul>