jQuery - mouseover/mouseout with multiple divs

12.1k views Asked by At

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);
});
2

There are 2 answers

4
user113716 On BEST ANSWER

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.

0
Matthew Davis On

This works for me on IE. Hope it helps.

$("#topbarVis").hover(function(){   $("#topbar").animate({height:"100%"}, 300); },function(){   $("#topbar").animate({height:"0%"}, 300); }); 

Using this as the CSS.

#topbar {   width: 100%;   height:0px;   background-color: #000; }