Reputation: 25
Trying to make a simple jquery drop down here, here's my code so far:
HTML:
<ul id="nav">
<li>
<a href="">Cats</a>
<ul>
<li><a href="">Tigers</a></li>
<li><a href="">Lions</a></li>
<li><a href="">Leopards</a></li>
</ul>
</li>
<li>
<a href="">Dogs</a>
<ul>
<li><a href="">Wolves</a></li>
<li><a href="">Dingos</a></li>
<li><a href="">Dholes</a></li>
</ul>
</li>
</ul>
CSS:
ul#nav { border: 1px solid #ccc; overflow: hidden; background: #eee; padding: 0; }
ul#nav li { display: block; float: left; border-right: 1px solid #ccc; padding: 10px 20px; }
ul#nav li ul { display: none; border: 1px solid #ccc; overflow: hidden; position: absolute; background: #eee; width: 100px; padding: 0; margin: 10px 0 0 -20px; border-bottom: none; }
ul#nav li ul li { display: block; float: left; width: 100%; border-bottom: 1px solid #ccc; }
jQuery:
$(document).ready(function() {
$('ul#nav > li > a').mouseover(function() {
$(this).parent().find('ul').slideDown('fast');
});
$('ul#nav > li > a').mouseout(function() {
$(this).parent().find('ul').slideUp('fast');
});
});
Problem is now when the user no longer hovers over the nav link the drop down ul goes away. I need it to go away if the user is not hovering over the nav link OR hovering over the drop down ul. How to do this?
Upvotes: 0
Views: 2044
Reputation: 35319
$(document).ready(function() {
$('ul#nav > li').hover(function() {
$(this).children('ul').slideDown('fast');
},function() {
$(this).children('ul').stop(true, true).slideUp('fast');
});
});
I made it a hover just to shorten it up a bit, the main thing however, is having it drop down on the li rather than the a, because the li will expand to hold the contents, so you wont actually leave the li when hovering over the new elements.
Upvotes: 2
Reputation: 7494
Your code was binding mouseout on anchor, when mouse is out of this and hover over ul the mouseout event fires.
try to bind event in ul#nav > li, replace your code by that:
$('ul#nav > li').mouseenter(function(){
clearTimeout($(this).data('timeoutId'));
$(this).find('ul').slideDown('fast');
}).mouseleave(function(){
var someelement = this;
var timeoutId = setTimeout(function(){ $(someelement).find('ul').fadeOut("slow");}, 650);
$(someelement).data('timeoutId', timeoutId);
});
You can determine a timeout, its increase navegability and user xp
Upvotes: 0