Reputation: 219
so i have a simple navbar with a dropdown menu for when a user hovers on the more tab. i want to hide the dropdown menu when the user mouses out of the categories div.
problem is that when the user mouses into a ul li, the dropdown closes. how can i set it so that the function ignores the ul li within the categories div. tried categories > * but didn't work.
<div id="navbar">
<ul>
<li>tab1</li>
<li>tab2</li>
<li id="moretab">more</li>
</ul>
</div>
<div id="categories">
<ul>
<li>cats</li>
<li>dogs</li>
</ul>
</div>
$("#moretab").hover(function(){
$("#categories").css("visibility","visible");
});
$("#categories").mouseout(function() {
$("#categories").css("visibility","hidden");
});
Upvotes: 12
Views: 58214
Reputation: 1061
Jquery hover plugin includes both mouseenter and mouseleave function and following code works fine for me.
javascript:
$(document).ready(function(){
$('.dropdown').hover(
function(){
$(this).children('.sub-menu').slideDown('fast');
},
function () {
$(this).children('.sub-menu').slideUp('fast');
});
});
Upvotes: 4
Reputation: 99
Few things:
add a delay from mouseleave, which is a preferable user experience
<div id="navbar">
<ul>
<li>tab1</li>
<li>tab2</li>
<li id="moretab">more
<div id="categories">
<ul>
<li>cats</li>
<li>dogs</li>
</ul>
</div>
</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#moretab").hover(function(){
$("#categories").slideDown("fast");
clearTimeout(debounce);
});
$("#moretab").mouseleave (function() {
debounce = setTimeout(closeMenu,400);
});
var debounce;
var closeMenu = function(){
$("#categories").slideUp("fast");
clearTimeout(debounce);
}
});
</script>
Upvotes: 2
Reputation: 7969
This might help ! Hide the "sub_menu" first.
//html
<ul>
<li id = "menu"> <a href ="#"> Settings </a>
<ul id = "sub_menu">
<li> <a href ="#"> page 1</a></li>
<li> <a href ="#"> page 2</a></li>
</ul>
</li>
<li>SomeLink</li>
<li>SomeLink 2</li>
</ul>
//Javascript
$("#menu").hover(function() {
$("#sub_menu").show();
}, function() {
$("#sub_menu").hide();
});
Upvotes: 2
Reputation: 762
$(document).ready(function () {
$("#moretab").mouseenter(function(){
$("#categories").show();
});
$("#categories, #moretab").mouseleave(function(){
$("#categories").hide();
});
});
Upvotes: 20
Reputation: 10902
The easiest answer is how you would do it without jQuery: put the dropdown in the triggering element (e.g. dropdown list in a list item in the navigation list).
If you want something less straightforward, mouseleave
might help.
Upvotes: 16