I have a hidden div nested inside a larger div, and set it up so when you mouseover the larger div, the hidden div slides down. On mouseout, the div slides back. The problem is, when the mouse goes over the smaller div, it tries to slide it back up because the mouseout event was triggered. How can I prevent the div from hiding again until the mouse is over neither div?
html:
<div id="topbarVis" class="col1 spanall height1 wrapper">
<div id="topbar"></div>
</div>
(the extra classes are part of a modular css system and define the width and height, among other things, of #topbarVis
css:
#topbar {
width: 100%;
height: 30px;
margin-top: -25px;
background-color: #000;
}
js:
// On Mouseover -> Show
$("#topbarVis").mouseover(function(){
$("#topbar").animate({marginTop:0}, 300);
});
// On Mouseout -> Hide
$("#topbarVis").mouseout(function(){
$("#topbar").animate({marginTop:-25}, 300);
});
Use mouseenter/mouseleave
instead:
$("#topbarVis").mouseenter(function(){
$("#topbar").animate({marginTop:0}, 300);
})
.mouseleave(function(){
$("#topbar").animate({marginTop:-25}, 300);
});
...or just use the hover()
(docs) method which is a shortcut for mouseenter/mouseleave
:
$("#topbarVis").hover(function(){
$("#topbar").animate({marginTop:0}, 300);
},function(){
$("#topbar").animate({marginTop:-25}, 300);
});
The reason is that the nature of mouseover/mouseout
is such that it bubbles. So it will fire when any descendants of the element get the events. Whereas mouseenter/mouseleave
don't bubble.
The only browser that actually supports the non-standard mouseenter/mouseleave
events is IE, but jQuery replicates its behavior.