Here is a simple html+css+js code
var myDiv = document.getElementById('myDiv');
myDiv.addEventListener('mouseenter', function() {
console.log('Mouse entered the div');
});
myDiv.addEventListener('mouseleave', function() {
console.log('Unfortunately this message happens when we enter the smaller div');
});
#myDiv {
width: 300px;
height: 300px;
background-color: yellow;
position: absolute;
}
#smaller {
border: 1px solid red;
width: 100px;
height: 100px;
position: absolute;
top: 100px;
left: 100px;
}
<div>
<div id="myDiv"></div>
<div id="smaller">
</div>
</div>
The issue here is mouseleave triggers when the mouse appears above the second element. Any nice and simple solution to avoid that? Tried another events. No luck.
P.S. JS solution is preferable. CSS hover is not the way to go for my case.
The important note – divs are on the same level (the second div is not a child of the first div).
4
Answers
Nest the
#smaller
div
inside of the#myDiv
div
to fix the issue.Place the
#smaller
div
inside of the#myDiv
. This counts the smaller div as part of the#myDiv
div
and doesn’t trigger yourmouseleave
event listener. This shouldn’t mess with your structure since the#smaller
div
is already utilizingposition: absolute;
.If you want to keep the HTML structure as it is you can put a
pointer-events: none;
on the smaller element.The way you describe it just put the event on the containing element and you are good to go.
One option is to use
relatedTarget
and a control flag to check if you were entering the smaller div(s).If you want
mouseenter
to trigger again when entering from the smaller div, you can remove the control flag.