Tuesday, April 6, 2010

onMouseOut Problem Solved

Hey All,
I was asked to develop a popup for a client, that should disappear on mouseout, but when I placed the onmouseout event on the parent container div of the popup, it triggered even entering into its child divs or elements, although it has never left the boundary of the parent container div.
If you want to understand the whole process look at the Example otherwise got to the solution section.

EXAMPLE:


<div id="parentDiv" onmousseout="closeDiv();">

in only one div

in only one div

in only one div

in only one div
</div>


When you bring your mouse to the parentdiv, nothing happens. When you leave this parentdiv the closeDiv function is called, which is perfectly right.

Now consider the following situation:

<div id="parentDiv" onmousseout="closeDiv();">
in Parent div

in Parent div

in Parent div

in Parent div


<div id="childDiv">
in Child

in Child

in Child

in Child

</div>
</div>

In this situation the onmouseout event does not work properly due to a phenomenon called bubbling. When you bring mouse to the parentDiv, nothing happens. When the mouse enters to the childDiv area the onmouseout event of the parentDiv is triggered and the popup closes which is not the desired behaviour.

SOLUTION:

I thought a bit on this and came up with this work around.

<script type="text/javascript">
var inPopUp=0;
function setIn(){
inPopUp=1;
}
function setOut(){
inPopUp=0;
}
function closeDiv() {
if (inPopUp==0){
alert("close");
}
}
</script>
<div id="parentDiv" onmousseout="setOut();setTimeout('closeDiv();',1000)">
in Parent div

in Parent div

in Parent div

in Parent div


<div id="childDiv" onmouseover="setIn();">
in Child

in Child

in Child

in Child

</div>
</div>


Hope this solution may help someone out there :) .

NOTE: All the above details are also valid for tables and rows instead of divs.