Search code examples
cssjquerymouseenterjquery-hover

Conflict between mouseenter event and absolute position of the elements


i have a div containing multiple divs with absolute position, i want to handle the mouse enter event for the parent div i use this fiddle: fiddle it doesnt works correctly is their any other way to handle this problem ?

HTML Markup

<div id="content">
SYDNEY (Reuters) - An Australian man had his driving licence suspended for 10 months and was fined after he was
 <div class="abs"></div>
caught driving a scooter made of a motorised beer cooler capable of carrying several dozen drinks -- after knocking back a few.
</div>
<div id="output">   
</div>    

SCRIPT

$(function() {
var output = $("#output");
$("#content")
  .mouseenter(function(e){
    output.text("I'm in!");
}).mouseout(function(e) {
    output.text("I'm out!"); 
});
});​


#content {
background-color:#cccc99;   
position:relative;     
}
.abs{
 position:absolute;
 top:0px;
 left:70px;
 background-color:red; 
 width:30px;
 height:30px;   
 }​

Solution

  • You're halfway there yourself. Because the mouseover and mouseout events bubble, they will trigger multiple times as you mouseover and mouseout of child elements of the element your event handlers are watching. jQuery provides the IE-inspired mouseenter and mouseleave events, which only trigger for mouse events on the watched elements themselves, and are not triggered for events on the element's children. Use the mouseover and mouseleave events, and your code will work as expected. See this updated fiddle. Alternatively, use the jQuery hover syntax, which internally uses the mouseenter and mouseleave events, wrapped in a convenient syntax.