Search code examples
jquerynavigationmouseoutmouseenter

jQuery Navigation Menu - Sub Menu Disappearing on MouseOut


I am developing my own jQuery Navigation Menu and have run into a bit of a problem as the sub-menus disappear as soon as the focus is taken away from the selection on the main navigation menu. I know there must be a simple solution to this but I've spent hours on this and figured it was time for some help.

Here is the code below:

jQuery:

$(document).ready(function() {

        $('.myMenu li ul').hide(); //hide all sub menus

        $('.myMenu > li').mouseenter(function() {
            $(this).find('ul').stop(true, true).fadeIn("fast");
        });

        $('.myMenu > li').mouseout(function() {
            $(this).find('ul').stop(true, true).fadeOut("fast");
        });
    });

HTML:

<div id="navigation">
<ul class="myMenu">
    <li><a href="#">Main 1</a></li>
    <li><a href="#">Main 2</a>
        <ul>
            <li><a href="#">Sub 1</a></li>
            <li><a href="#">Sub 2</a></li>
            <li><a href="#">Sub 3</a></li>
            <li><a href="#">Sub 4</a></li>
            <li><a href="#">Sub 5</a></li>
            <li><a href="#">Sub 6</a></li>
            <li><a href="#">Sub 7</a></li>
            <li><a href="#">Sub 8</a></li>
            <li><a href="#">Sub 9</a></li>
        </ul>
    </li>
    <li><a href="#">Main 3</a>
        <ul>
            <li><a href="#">Sub 1</a></li>
            <li><a href="#">Sub 2</a></li>
            <li><a href="#">Sub 3</a></li>
        </ul>
    </li>  
    <li><a href="#">Main 4</a></li>
    <li><a href="#">Main 5</a></li>
    <li><a href="#">Main 6</a></li>
    <li><a href="#">Main 7</a></li>
    <li><a href="#">Main 8</a></li>
</ul>
</div>

Any help would be gladly appreciated!


Solution

  • This is merely your exact code above converted into the correct format for the .hover() method which conveniently combines mouseenter and mouseleave into one method.

    $('.myMenu > li').hover(
        function() {
            $(this).find('ul').stop(true, true).fadeIn("fast");
    }, 
        function() {
            $(this).find('ul').stop(true, true).fadeOut("fast");
    });
    

    It seems to solve the problem as you described. "Main 2" and "Main 3" stay open when you're within their corresponding sub-menus.

    http://jsfiddle.net/Zr5ca/1