randmath
randmath

Reputation: 181

jQuery drop down menu - hide inner ul when user clicks anywhere outside inner ul

I have a jQuery drop down menu and everything works well except when the user clicks outside of the inner ul (e.g. the rest of the body or document) the inner ul does not pull back up. Any ideas? Here's my code:

$(document).ready(function() {
    $("#cp-nav ul li").click(function() {
        $("#cp-nav ul ul").slideUp("fast", function(){});

        $("ul", this).slideDown("fast", function(){
            $("ul", this).slideUp("fast");
        });
    });
});

So maybe do something like:

$("ul", !this).slideUp("fast", function(){});

I am kind of new to jQuery and JavaScript, and I tried to look around for my problem but it's kind of difficult to phrase. I also noticed there is a callback function for jQuery's slideUp, and I can not figure out how to use it. Any help? It would be much appreciated! :-)

Edit

HTML:

<nav id="cp-nav">
    <ul>
        <li><a href="home.html">Home</a></li>
        <li>
            <a href="products.html">Products</a>
            <ul>
               <li>Design Platforms</li>
               <li>3D Animation</li>
               <li>Graphic Design</li>
               <li>Python</li>
            </ul>
        </li>
        <li>
            <a href="products.html">About</a>
            <ul>
               <li>Company History</li>
               <li>CEO &amp; Founder</li>
               <li>etc.</li>
               <li>etc.</li>
            </ul>
        </li>
        <li>
            <a href="products.html">etc.</a>
            <ul>
               <li>etc.</li>
               <li>etc.</li>
               <li>etc.</li>
               <li>etc.</li>
            </ul>
        </li>
    </ul>
</nav>

Upvotes: 2

Views: 639

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196256

This would do it

$(document).ready(function() {
    $("#cp-nav").click(function(e){
        e.stopPropagation(); // this stops the bubbling from going any higher
    });
    $('body').click(function(){ // this is only reached if the clicks comes outside the #cp-nav
        $("#cp-nav ul ul").slideUp('fast');
    });
    $("#cp-nav ul li").click(function() {
        $("#cp-nav ul ul").slideUp("fast", function(){});

        $("ul", this).slideDown("fast", function(){
            $("ul", this).slideUp("fast");
        });
    });
});

Upvotes: 1

Related Questions