Forked from toruta39/preventAdditionalMouseEvent.html
Created
April 15, 2023 12:02
-
-
Save kongondo/4e64b4e9f1e53c855bba26b984e81dfc to your computer and use it in GitHub Desktop.
Prevent mouseout/mouseover event triggered when moving onto/from a child element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en-US"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Prevent additional mouse event</title> | |
</head> | |
<body> | |
<div id="ele" style="width: 300px; height: 300px; background-color: #0FF;"> | |
This is the parent element. | |
<div style="width: 200px; height: 200px; background-color: #FFF;"> | |
This is the child element. | |
<div style="width: 150px; background-color: #000; color: #FFF"> | |
Grand child element. | |
</div> | |
</div> | |
</div> | |
<script type="text/javascript" src="preventAdditionalMouseEvent.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ele = document.getElementById("ele"); | |
var over = 0, out = 0; | |
//Detect if otherNode is contained by refNode | |
function isParent(refNode, otherNode) { | |
var parent = otherNode.parentNode; | |
do { | |
if (refNode == parent) { | |
return true; | |
} else { | |
parent = parent.parentNode; | |
} | |
} while (parent); | |
return false; | |
} | |
ele.addEventListener("mouseover", function(ev){ | |
//Make sure that the mouseover event isn't triggered when moving from a child element | |
//or bubbled from a child element | |
if (!isParent(this, ev.relatedTarget) && ev.target == this){ | |
//Event handling code here | |
this.style.backgroundColor = "#FF0"; | |
this.childNodes[0].nodeValue = "Mouseover: " + ++over +", Mouseout: " + out + "."; | |
} | |
}, false); | |
ele.addEventListener("mouseout", function(ev){ | |
//Make sure that the mouseout event is triggered when moving onto a child element | |
//or bubbled from a child element | |
if (!isParent(this, ev.relatedTarget) && ev.target == this){ | |
//Event handling code here | |
this.style.backgroundColor = "#0FF"; | |
this.childNodes[0].nodeValue = "Mouseover: " + over +", Mouseout: " + ++out + "."; | |
} | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment