onmouseout onmouseover element parent event handlers problem – child events cause parent to trigger

onmouseout  onmouseover event handlers Problem causes child elements event handlers to fire / trigger /actuate – Use mouseenter mouseleave on the parent element instead. It will prevent the child elements from firing as well.

 
[SHORTCODE_Insert_Google_Adsence_Here]
Recently – I found myself in the need of a DIV within a DIV – where they both needed mouse events to be triggered independently, as the user mouses over the parent and then child DIV. The mousing of the child div – caused the parent “onmouseout” to actuate unnecessarily.

The solution is to NOT use “onmouseout” or “onmouseover”.
As “onmouseout”  or “onmouseover” are subject to “Event bubbling” as it is known.  “event on element2 takes precedence. This is called event bubbling”. http://www.quirksmode.org/js/events_order.html

 

The Problem:

The mousing of the child div that uses onmouseover – causes the parent “onmouseout” to trigger.

 

The Solution:

Along with JQUERY – Use the “mouseenter” and “mouseleave” on the parent div instead – the child elements will not effect the “onmouseleave”

Use Example:

 

[code]
  <style>
.Child_Div_Button{
    float:left;
    cursor:pointer;
    height:100px;
    width:100px;
    background-color:#CCC;
    border:#000 thin solid;
    margin:2px;
    padding:2px;
}

.Child_Div_Button:hover{
    background-color:#FFF;
}
</style>

<div id="Parent_Div_Container" style="height:300px; width:300px; border:#333 thin solid; background-color:#D2FFFF;">
Parent Div
<div id="button_container"> 
        <div>
        Button 1 Child Div
        </div>

        <div>
        Button 2 Child Div
        </div>
    </div>

</div>

<script type="text/javascript">

      document.getElementById('button_container').style.display = 'none';// initiate

        document.getElementById('Parent_Div_Container').addEventListener('mouseenter',function(){
            document.getElementById('button_container').style.display = 'block';
        });
        document.getElementById('Parent_Div_Container').addEventListener('mouseleave',function(){
            document.getElementById('button_container').style.display = 'none';
        });

</script>

[/code]

(

It looks like the “addEventListener(‘mouseenter'” and “addEventListener(‘mouseleave'” work on the latest version of Firefox (15.0.1) WITHOUT the need for JQUERY – But Chrome, IE and Safari, all seem to need the jquery library for this to work. Is that to say that mozila now fully supports the use of mouseenter and mouseleave?!?! If so .. YAY! for the browser that actually does things to help developers : )

)

Leave a Reply