Reputation: 181
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! :-)
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 & 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
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