I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout.
Below is the code snippet causing the problem:
<html>
<head>
<style type="text/css">
#layer1 {
width: 370px;
height: 220px;
background-color: yellow;
}
#layer2 {
position: relative;
width: 130px;
height: 47px;
top: 10px;
left: 10px;
background-color: #CC0066;
}
#layer3 {
position: relative;
width: 200px;
height: 100px;
top: 10px;
left: 150px;
background-color: #334466;
}
#button1 {
position: relative;
top: 4px;
left: 4px;
}
#button2 {
position: relative;
top: 4px;
left: 4px;
}
</style>
<body>
<div id="layer1">
<div id = "layer2">
<input type="submit" id = "button1" value="Button 1 (onclick)"></input>
</div>
<div id = "layer3">
<input type="submit" id = "button2" value="Button 2 (onmouseout)"></input>
</div>
</div>
<script type="text/javascript">
document.getElementsByTagName("body")[0].addEventListener("click", function() {print(event);}, false);
document.getElementsByTagName("div")[0].addEventListener("click", function() {print(event);}, false);
document.getElementsByTagName("div")[1].addEventListener("click", function() {print(event);}, false);
document.getElementsByTagName("input")[0].addEventListener("click", function() {print(event);}, false);
document.getElementsByTagName("div")[2].addEventListener("mouseout", function() {print(event);}, false);
document.getElementsByTagName("input")[1].addEventListener("mouseout", function() {print(event);}, false);
function print(elem) {
alert("JavaScript alert\n\n" +
"Element\n" +
" Type: " + elem.relatedTarget.tagName +
"\n Id: " + elem.relatedTarget.id +
"\nEvent's name: " + elem.type +
"\nMouse's coordinates" +
"\n Screen: " + elem.screenX + ", " + elem.screenY +
"\n Window: " + elem.clientX + ", " + elem.clientY +
"\n HTML item: " + elem.offsetX + ", " + elem.offsetY);
}
</script>
</body>
</html>
Error occurs on clicking the item: https://i.stack.imgur.com/KJ5We.png
However, it functions correctly with mouseout events: https://i.stack.imgur.com/kuwrH.png
I am puzzled by what could be wrong since I'm using the same function, only changing the event type.
Thank you in advance.