Forked from toruta39/preventAdditionalMouseEvent.html
Created
August 20, 2020 01:07
-
-
Save bradkrane/18a6779ed9c26a558d7fc0ef8482d3cc to your computer and use it in GitHub Desktop.
Prevent mouseout/mouseover event triggered when moving onto/from a child element
This file contains hidden or 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 hidden or 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