I have a nested list structure that I am working with:
<ul class="menu-wrapper">
<li>
<a href="#">Menu item</a>
<ul class="sub-menu">
<li>
<a href="#">Subitem-1</a>
<ul>
<li>Sub-Subitem-1</li>
<li>Sub-Subitem-2</li>
<li>Sub-Subitem-3</li>
</ul>
</li>
<li>
<a href="#">Subitem-2</a>
<ul>
<li>Sub-Subitem-1</li>
<li>Sub-Subitem-2</li>
<li>Sub-Subitem-3</li>
</ul>
</li>
</ul>
</li>
</ul>
My current task involves adding and removing the .active
class when hovering over certain elements. Here is my existing jQuery code for handling these interactions:
$('ul.menu-wrapper').children().hover(
function() {
let subMenu = $(this).find('ul.sub-menu').first()
subMenu.addClass('active')
subMenu.children().first().addClass('active')
},
function() {
let subMenu = $(this).find('ul.sub-menu').first()
subMenu.removeClass('active')
}
)
Now, I need to enhance this functionality by ensuring that when hovering over li
items within the ul.sub-menu
, the .active
class should be applied dynamically to the hovered item. This requires another hover event on the submenu children:
$('ul.menu-wrapper').children().hover(
function() {
...
subMenu.children().hover(
function() {
$(this).addClass('active')
},
function() {
$(this).removeClass('active')
}
)
},
function() {
...
}
)
In order to maintain an .active
state at all times, even when transitioning between parent and child elements, I need to modify the behavior of the code to ensure that there is always at least one ul.sub-menu > li
item with the .active
class. Currently, the default behavior removes the class when moving from a submenu back to the parent list item. How can I adjust this to meet the desired outcome?
For a live demonstration, visit: https://jsfiddle.net/5Lwyh3xs/