jQuery MouseEnter and MouseOut events with .toggle() reverse when the mouse is already over the element onLoad?
Question
I have a dropdown menu working great with the following code:
$('#menu ul li').mouseenter(function(){
$(this).children(".dropdown").toggle();
}).mouseleave(function(){
$(this).children(".dropdown").toggle();
});
This works as you would expect. The issue is that if the mouse is already mouseenter
on the $('#menu ul li')
when the $(document).ready(function(){ })
is fired, the toggle works the other way round?
How can I avoid this?
Solution
don't you want to do show()
on mouseenter
and hide()
on mouseleave
?
OTHER TIPS
Instead of just calling toggle
with no arguments, your mouse event handlers can pass in explicit boolean showOrHide
values. Pass true
to toggle()
in the mouseenter
routine, and false
in mouseleave
. Or do as suggested by the other answer and just use show
and hide
.
When you load the document without moving the mouse, no mouseover action will be toggled until you move the mouse. But i think mouseover is toggled as your mouse moves, event if it's already "over" onLoad.
What about this code ? Anyways, i think your bug comes from mouseout not being toggled because JS only checks every x ms, and if you move too fast, it gets out of the div without calling the event.
$('#menu ul li').mouseenter(function(){
// hide all other divs
$(".dropdown").hide(0);
// show the div we want
$(this).children(".dropdown").show(0);
}).mouseleave(function(){
$(".dropdown").hide(0);
});
If you don't care about animations, doing this with CSS is always a better way then with JS.
You'll need to set it up like this :
<div id="menu">
<ul>
<li>
Menu 1
<div class="dropdown">Sub1</div>
<div class="dropdown">Sub2</div>
</li>
<li>
Menu 2
<div class="dropdown">Sub1</div>
<div class="dropdown">Sub2</div>
</li>
</ul>
</div>
CSS:
.dropdown { display: none; position: relative; }
#menu li:hover .dropdown { display: block; }