Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect mouse is over a child element in jQuery?

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?

like image 639
netdjw Avatar asked Jan 07 '14 12:01

netdjw


1 Answers

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.

like image 166
Geoffrey Xia Avatar answered Oct 03 '22 16:10

Geoffrey Xia