Search code examples
jquerymenudrop-down-menuexpand

jQuery dropdown menu should expand if parent is active


I'm making a simple dropdown menu in jQuery. And it works fine. I'm having a problem though.

The problem is, that i need to keep the active page dropdown expanded In the example below the sub-menu that has the .inpath parent needs to always stay expanded. If you hover on another menu-item it should show the relevant subpages and when you hover out return to show the active subpages. Any help is greatly appriciated :-)!

My html:

<div id="menu">

            <ul>

                <li><a href="">Hvem</a></li>
                <li><a href="">Hvad</a>
                    <ul>
                    <li><a href="">Produkter</a></li>
                    <li><a href="">Leveringer</a></li>
                    </ul>
                </li>

                <li class="inpath"><a href="">Hvordan</a>

                    <ul>

                        <li><a href="">Reklame</a></li>
                        <li><a href="">PR</a></li>
                        <li><a href="">Websites</a></li>
                        <li><a href="">Illustrationer</a></li>

                    </ul>

                </li>
                <li class="last-item"><a href="">Sådan!</a></li>

            </ul>

            <div class="clear"><!--clearfix--></div>

        </div>

My jQuery:

 <script type="text/javascript">
        //mouseenter, mouseover, hover
        // mouseleave, mouseout,
    $(document).ready(function () { 
        $('#menu ul li ul').hide();
        $('#menu li').hover(
            function () {
                //show its submenu
                $('ul', this).slideDown(100);

            }, 
            function () {
                //hide its submenu
                $('ul', this).slideUp(100);         
            }
        );

    });

        </script>

Solution

  • try removing .inpath from the original hide() and the hover(). You also need more specific selects using the > (direct descendant selector).

    $(document).ready(function() {
        $('#menu > ul > li:not(.inpath) ul').hide();
        $('#menu > ul > li:not(.inpath)').hover(
    
        function() {
            $('ul', this).slideDown(100);
            $('#menu li.inpath ul').hide();
        }, function() {
            $('ul', this).slideUp(100);
            $('#menu li.inpath ul').show();
        });
    });
    

    http://jsfiddle.net/MGkQC/7/