AKor
AKor

Reputation: 8882

Showing a submenu on hover of the parent link, then keeping it visible until the mouse leaves the sub menu?

I have a menu arranged like this:

<ul class="parent-menu">
  <li class="menu-item">
    <a class="menu-item-link" href="#">Link</a>
    <ul class="sub-menu">
      <!-- sub menu list items -->
    </ul>
  </li>
  <!-- more parent menu list items -->
</ul>

The .sub-menu elements are hidden by default.

I'm using the following jQuery to show/hide the submenus perfectly fine:

$('.menu-item > a').hover(function() {
  $(this).find('.sub-menu').toggle();
})

Of course, they disappear as soon as the mouse leaves the .menu-item > a element. I can't figure out a way to "handoff" the second half of the .toggle() event to work as basically a .mouseleave() on the entire .sub-menu element.

So when a user hovers on a parent menu item, they are presented with a sub menu, and should be able to hover at their leisure and select a sub menu item.

How would I go about this?

Upvotes: 0

Views: 986

Answers (2)

AKor
AKor

Reputation: 8882

Figured it out actually. I was overcomplicating things by using .hover() and found that I could simply use mouseenter() and mouseleave() separately, but using the latter on the parent element of both the main menu item and its submenu. So when your mouse enters the parent menu item link, it shows its sub menu (I have multiple, so I had to use $(this) and find() or siblings() instead of hardcoding it). And when the mouse leaves the parent of both (so either the main link or the sub menu itself) it becomes hidden, as it should be.

Here's the code:

$('.menu-item > a').mouseenter(function() {
  $(this).siblings('.sub-menu').show();

});

$('.menu-item').mouseleave(function() {
  $(this).find('.sub-menu').hide();
});

Upvotes: 1

graphical_force
graphical_force

Reputation: 35

display = false;
$('.sub-menu').toggle( display );

$('.parent-menu').mouseenter(function() {
  $('.sub-menu').toggle("slow");
});

$('.parent-menu').mouseleave(function() {
  $('.sub-menu').toggle("slow");
});

Not sure if you wanted each one to separately or together. This will open them all.

Upvotes: 0

Related Questions