[javascript] Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

I am having trouble with the onmouseout function in an absolute positoned div. When the mouse hits a child element in the div, the mouseout event fires, but I do not want it to fire until the mouse is out of the parent, absolute div.

How can I prevent the mouseout event from firing when it hits a child element WITHOUT jquery.

I know this has something to do with event bubbling, but I am having no luck on finding out how to work this out.

I found a similar post here: How to disable mouseout events triggered by child elements?

However that solution uses jQuery.

This question is related to javascript css dom-events onmouseout

The answer is


Try mouseleave()

Example :

<div id="parent" mouseleave="function">
   <div id="child">

   </div>
</div>

;)


Use onmouseleave.

Or, in jQuery, use mouseleave()

It is the exact thing you are looking for. Example:

<div class="outer" onmouseleave="yourFunction()">
    <div class="inner">
    </div>
</div>

or, in jQuery:

$(".outer").mouseleave(function(){
    //your code here
});

an example is here.


On Angular 5, 6 and 7

<div (mouseout)="onMouseOut($event)"
     (mouseenter)="onMouseEnter($event)"></div>

Then on

import {Component,Renderer2} from '@angular/core';
...
@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit, OnDestroy {
...
 public targetElement: HTMLElement;

 constructor(private _renderer: Renderer2) {
 }

 ngOnInit(): void {
 }

 ngOnDestroy(): void {
  //Maybe reset the targetElement
 }

 public onMouseEnter(event): void {
  this.targetElement = event.target || event.srcElement;
  console.log('Mouse Enter', this.targetElement);
 }

 public onMouseOut(event): void {
  const elementRelated = event.toElement || event.relatedTarget;
  if (this.targetElement.contains(elementRelated)) {
    return;
  }
  console.log('Mouse Out');
 }
}

If you added (or have) a CSS class or id to the parent element, then you can do something like this:

<div id="parent">
  <div>
  </div>
</div>

JavaScript:
document.getElementById("parent").onmouseout = function(e) {
  e = e ? e : window.event //For IE
  if(e.target.id == "parent") {
    //Do your stuff
  }
}

So stuff only gets executed when the event is on the parent div.


I just wanted to share something with you.
I got some hard time with ng-mouseenter and ng-mouseleave events.

The case study:

I created a floating navigation menu which is toggle when the cursor is over an icon.
This menu was on top of each page.

  • To handle show/hide on the menu, I toggle a class.
    ng-class="{down: vm.isHover}"
  • To toggle vm.isHover, I use the ng mouse events.
    ng-mouseenter="vm.isHover = true"
    ng-mouseleave="vm.isHover = false"

For now, everything was fine and worked as expected.
The solution is clean and simple.

The incoming problem:

In a specific view, I have a list of elements.
I added an action panel when the cursor is over an element of the list.
I used the same code as above to handle the behavior.

The problem:

I figured out when my cursor is on the floating navigation menu and also on the top of an element, there is a conflict between each other.
The action panel showed up and the floating navigation was hide.

The thing is that even if the cursor is over the floating navigation menu, the list element ng-mouseenter is triggered.
It makes no sense to me, because I would expect an automatic break of the mouse propagation events.
I must say that I was disappointed and I spend some time to find out that problem.

First thoughts:

I tried to use these :

  • $event.stopPropagation()
  • $event.stopImmediatePropagation()

I combined a lot of ng pointer events (mousemove, mouveover, ...) but none help me.

CSS solution:

I found the solution with a simple css property that I use more and more:

pointer-events: none;

Basically, I use it like that (on my list elements):

ng-style="{'pointer-events': vm.isHover ? 'none' : ''}"

With this tricky one, the ng-mouse events will no longer be triggered and my floating navigation menu will no longer close himself when the cursor is over it and over an element from the list.

To go further:

As you may expect, this solution works but I don't like it.
We do not control our events and it is bad.
Plus, you must have an access to the vm.isHover scope to achieve that and it may not be possible or possible but dirty in some way or another.
I could make a fiddle if someone want to look.

Nevertheless, I don't have another solution...
It's a long story and I can't give you a potato so please forgive me my friend.
Anyway, pointer-events: none is life, so remember it.


Although the solution you referred to uses jquery, mouseenter and mouseleave are native dom events, so you might use without jquery.


If you're using jQuery you can also use the "mouseleave" function, which deals with all of this for you.

$('#thetargetdiv').mouseenter(do_something);
$('#thetargetdiv').mouseleave(do_something_else);

do_something will fire when the mouse enters thetargetdiv or any of its children, do_something_else will only fire when the mouse leaves thetargetdiv and any of its children.


instead of onmouseout use onmouseleave.

You haven't showed to us your specific code so I cannot show you on your specific example how to do it.

But it is very simple: just replace onmouseout with onmouseleave.

That's all :) So, simple :)

If not sure how to do it, see explanation on:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out

Peace of cake :) Enjoy it :)


Here's a more elegant solution based on what came below. it accounts for event bubbling up from more than one level of children. It also accounts for cross-browser issues.

function onMouseOut(this, event) {
//this is the original element the event handler was assigned to
   var e = event.toElement || event.relatedTarget;

//check for all children levels (checking from bottom up)
while(e && e.parentNode && e.parentNode != window) {
    if (e.parentNode == this||  e == this) {
        if(e.preventDefault) e.preventDefault();
        return false;
    }
    e = e.parentNode;
}

//Do something u need here
}

document.getElementById('parent').addEventListener('mouseout',onMouseOut,true);

There are two ways to handle this.

1) Check the event.target result in your callback to see if it matches your parent div

var g_ParentDiv;

function OnMouseOut(event) {
    if (event.target != g_ParentDiv) {
        return;
    }
    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.onmouseout = OnMouseOut;
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

2) Or use event capturing and call event.stopPropagation in the callback function

var g_ParentDiv;

function OnMouseOut(event) {

    event.stopPropagation(); // don't let the event recurse into children

    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.addEventListener("mouseout", OnMouseOut, true); // pass true to enable event capturing so parent gets event callback before children
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

I think Quirksmode has all the answers you need (different browsers bubbling behaviour and the mouseenter/mouseleave events), but I think the most common conclusion to that event bubbling mess is the use of a framework like JQuery or Mootools (which has the mouseenter and mouseleave events, which are exactly what you intuited would happen).

Have a look at how they do it, if you want, do it yourself
or you can create your custom "lean mean" version of Mootools with just the event part (and its dependencies).


If you have access to the element which the event is attached to inside the mouseout method, you can use contains() to see if the event.relatedTarget is a child element or not.

As event.relatedTarget is the element to which the mouse has passed into, if it isn't a child element, you have moused out of the element.

div.onmouseout = function (event) {
    if (!div.contains(event.relatedTarget)) {
        // moused out of div
    }
}

var elem = $('#some-id');
elem.mouseover(function () {
   // Some code here
}).mouseout(function (event) {
   var e = event.toElement || event.relatedTarget;
   if (elem.has(e).length > 0) return;

   // Some code here
});

There are a simple way to make it work. The element and all childs you set a same class name, then:

element.onmouseover = function(event){
 if (event.target.className == "name"){
 /*code*/
 }
}

Thanks to Amjad Masad that inspired me.

I've the following solution which seems to work in IE9, FF and Chrome and the code is quite short (without the complex closure and transverse child things) :

    DIV.onmouseout=function(e){
        // check and loop relatedTarget.parentNode
        // ignore event triggered mouse overing any child element or leaving itself
        var obj=e.relatedTarget;
        while(obj!=null){
            if(obj==this){
                return;
            }
            obj=obj.parentNode;
        }
        // now perform the actual action you want to do only when mouse is leaving the DIV
    }

I've found a very simple solution,

just use the onmouseleave="myfunc()" event than the onmousout="myfunc()" event

In my code it worked!!

Example:

<html>
<head>
<script type="text/javascript">
   function myFunc(){
      document.getElementById('hide_div').style.display = 'none';
   }
   function ShowFunc(){
      document.getElementById('hide_div').style.display = 'block';
   }
</script>
</head>
<body>
<div onmouseleave="myFunc()" style='border:double;width:50%;height:50%;position:absolute;top:25%;left:25%;'>
   Hover mouse here
   <div id='child_div' style='border:solid;width:25%;height:25%;position:absolute;top:10%;left:10%;'>
      CHILD <br/> It doesn't fires if you hover mouse over this child_div
   </div>
</div>
<div id="hide_div" >TEXT</div>
<a href='#' onclick="ShowFunc()">Show "TEXT"</a>
</body>
</html>

Same Example with mouseout function:

<html>
<head>
<script type="text/javascript">
   function myFunc(){
      document.getElementById('hide_div').style.display = 'none';
   }
   function ShowFunc(){
      document.getElementById('hide_div').style.display = 'block';
   }
</script>
</head>
<body>
<div onmouseout="myFunc()" style='border:double;width:50%;height:50%;position:absolute;top:25%;left:25%;'>
   Hover mouse here
   <div id='child_div' style='border:solid;width:25%;height:25%;position:absolute;top:10%;left:10%;'>
      CHILD <br/> It fires if you hover mouse over this child_div
   </div>
</div>
<div id="hide_div">TEXT</div>
<a href='#' onclick="ShowFunc()">Show "TEXT"</a>
</body>
</html>

Hope it helps :)


I check the original element's offset to get the page coordinates of the element's bounds, then make sure the mouseout action is only triggered when the mouseout is out of those bounds. Dirty but it works.

$(el).live('mouseout', function(event){
    while(checkPosition(this, event)){
        console.log("mouseovering including children")
    }
    console.log("moused out of the whole")
})

var checkPosition = function(el, event){
    var position = $(el).offset()
    var height = $(el).height()
    var width = $(el).width()
    if (event.pageY > position.top 
|| event.pageY < (position.top + height) 
|| event.pageX > position.left 
|| event.pageX < (position.left + width)){
    return true
}
}

I make it work like a charm with this:

function HideLayer(theEvent){
 var MyDiv=document.getElementById('MyDiv');
 if(MyDiv==(!theEvent?window.event:theEvent.target)){
  MyDiv.style.display='none';
 }
}

Ah, and MyDiv tag is like this:

<div id="MyDiv" onmouseout="JavaScript: HideLayer(event);">
 <!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>

This way, when onmouseout goes to a child, grand-child, etc... the style.display='none' is not executed; but when onmouseout goes out of MyDiv it runs.

So no need to stop propagation, use timers, etc...

Thanks for examples, i could make this code from them.

Hope this helps someone.

Also can be improved like this:

function HideLayer(theLayer,theEvent){
 if(theLayer==(!theEvent?window.event:theEvent.target)){
  theLayer.style.display='none';
 }
}

And then the DIVs tags like this:

<div onmouseout="JavaScript: HideLayer(this,event);">
 <!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>

So more general, not only for one div and no need to add id="..." on each layer.


simply we can check e.relatedTarget has child class and if true return the function.

    if ($(e.relatedTarget).hasClass("ctrl-btn")){
        return;
    }

this is code worked for me, i used for html5 video play,pause button toggle hover video element

element.on("mouseover mouseout", function(e) {

    if(e.type === "mouseout"){

        if ($(e.relatedTarget).hasClass("child-class")){
            return;
        }

    }

});

For a simpler pure CSS solution that works in most cases, one could remove children's pointer-events by setting them to none

.parent * {
     pointer-events: none;
}

Browser support: IE11+


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to onmouseout

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery