I have a menu and I am trying to make level 3 for this menu. I need to add a class "show-submenu" for the submenu whose parent the user hovered over and remove that class if the user hovered over another menu item or clicked outside the menu.
For this I use Jquery.
For example, if user hovers li with the Refund policy I need to add the "show-submenu" class to "dropdown-menu" with the Sample page
if user hovers li with the Test page I need to add "show-submenu" class to "dropdown-menu" with the Contact
html
<li class="menu-item menu-item-has-children nav-item">
<a href="#" data-toggle="dropdown"class="dropdown-toggle nav-link show" >Pages</a>
<ul class="dropdown-menu show">
<li class="menu-item nav-item">
<a href="http://localhost/login-page/" class="dropdown-item">
Login page
</a>
</li>
<li class="menu-item menu-item-has-children dropdown nav-item">
<a href="http://localhost/refund_returns/" class="dropdown-item">
Refund policy
</a>
<ul class="dropdown-menu">
<li itemscope="itemscope" class="menu-item nav-item">
<a href="http://localhost/sample-page/" class="dropdown-item">
Sample page
</a>
</li>
</ul>
</li>
<li class="menu-item menu-item-has-children dropdown nav-item">
<a href="http://localhost/home-logos/" class="dropdown-item">
Test page
</a>
<ul class="dropdown-menu">
<li class="menu-item nav-item">
<a href="http://localhost/kontakt/" class="dropdown-item">
Contact
</a>
</li>
</ul>
</li>
</ul>
</li>
Jquery
jQuery(document).ready(function($) {
var timeout;
$('.dropdown-item').mouseleave(function() {
clearTimeout(timeout);
$(this).closest('.dropdown-menu').find('.dropdown-menu').first().addClass('show-submenu');
});
$('.dropdown-item').mouseenter(function() {
$(this).closest('.dropdown-menu').removeClass('show-submenu');
});
$(document).on('click', function(event) {
var target = $(event.target);
// Check if the clicked element is outside the menu
if (!target.closest('.dropdown-menu').length) {
$('.dropdown-menu').removeClass('show-submenu');
}
});
});
this code has several bugs.
- show-submenu added to "dropdown-menu show" ( ) but I need only one that belongs to current li
- I need to have only 1 show-submenu and remove it if user hover another menu item
2
Answers
I tested your
jQuery
code and this is working for me :show-submenu
class to closest parentdropdown-menu
when leaving focus ondropdown-item
show-submenu
classes on alldropdown-menu
when entering focus on adropdown-item
show-submenu
classes on alldropdown-menu
when clicking away from the menuYou need to add mouseenter and mouseleave on li element instead of dropdown-item so that it would stay visible even if you hover mouse to the child elements.
The below code will show the submenu when you hover the mouse and hide the same submenu when you leave the mouse from parent.