The code provided below will constantly display the cursor's coordinates right below the cursor:
function displayCursorCoordinates(e) {
var x = event.clientX;
var y = event.clientY;
var coordinates = "(" + x + ", " + y + ")";
document.getElementById("box").innerHTML = coordinates;
var bx = document.getElementById("box");
bx.style.left = e.pageX - 50;
bx.style.top = e.pageY + 20;
}
function hideCoordinates() {
document.getElementById("box").innerHTML = "";
}
div.relative {
position: relative;
width: 400px;
height: 300px;
border: 1px solid black;
}
div.abs {
position: absolute;
top: 100px;
right: 50px;
width: 200px;
height: 100px;
background-color: yellow;
}
<body onmousemove="displayCursorCoordinates(event)">
<div class="relative">
<div class="abs" onmousemove="displayCursorCoordinates(event)" onmouseout="hideCoordinates()"></div>
</div>
<div id="box" style="width:100px; height:30px; position:absolute"></div>
</body>
I want the coordinates to only show when the cursor is positioned over the yellow rectangle. If I modify
<body onmousemove="displayCursorCoordinates(event)">
to <body>
, the coordinates are hidden.
How can I ensure that the coordinates are only visible when hovering over the yellow rectangle?