I have a menu-submenu-subsubmenu construction in HTML like this:
<menu>
<li><a href="...">Item 1</a></li>
<li><ul>
<li><a href="...">Subitem 1</a></li>
<li><a href="...">Subitem 2</a></li>
<li><ul>
<li><a href="...">Sub-subitem 1</a></li>
<li><a href="...">Sub-subitem 2</a></li>
<li><a href="...">Sub-subitem 3</a></li>
</ul>
<a href="...">Subitem 3</a></li>
<li><a href="...">Subitem 4</a></li>
</ul>
<a href="...">Item 2</a>
</li>
<li><a href="...">Item 3</a></li>
<li><a href="...">Item 4</a></li>
...using whit this css formating:
menu {
display: block;
width: 200px;
}
/* hide subitems */
menu li ul,
menu li ul li ul {
display: none;
position: absolute;
}
/* set up positions */
menu li ul {
left: 200px;
width: 200px;
}
menu li ul li ul {
left: 400px;
width: 200px;
}
I use this jQuery code:
$(function() {
/* hide all submenu */
$('menu').find('ul').hide();
/* show submenu on mouseenter */
$('menu li a').mouseenter(function() {
$(this).parent().children('ul').show();
}).mouseleave(function() {
$(this).parent().children('ul').hide();
});
});
How can I detect mouse is leaving the element to their child? Or how can I get the child element to stay if it's necessary?
Change your code to be like this:
$(function() {
/* hide all submenu */
$('menu').find('ul').hide();
/* show submenu on mouseenter */
// here, just select the direct child
$('menu').find('li > a, li > ul').mouseenter(function() {
var time = new Date().getTime();
$(this).parent().find('ul').show().data('showing-time', time);
}).mouseleave(function() {
var leaveTime = new Date().getTime();
var $this = $(this);
window.setTimeout(function () {
var $ul = $this.parent().find('ul');
var beginTime = $ul.data('showing-time') || 0;
if (leaveTime > beginTime) {
$this.parent().find('ul').hide().data('showing-time', 0);
}
}, 100);
});
});
Hope this helps.
update
Code updated.
I suggest just put the sub menus next to the parent menu item(here, means li > a
element) to get a better result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With