Tuesday, November 8, 2022

[FIXED] How to let the coodinates of the cursor be shown below the cursor when hovering over a rectangle?

Issue

The following code always shows the coordinates of the cursor below the cursor:

function showCoords(e) {
  var x = event.clientX;
  var y = event.clientY;
  var coor = "(" + x + ", " + y + ")";
  document.getElementById("box").innerHTML = coor;
  var bx = document.getElementById("box");
  bx.style.left = e.pageX - 50;
  bx.style.top = e.pageY + 20;
}

function clearCoords() {
  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="showCoords(event)">
  <div class="relative">
    <div class="abs" onmousemove="showCoords(event)" onmouseout="clearCoords()"></div>
  </div>
  <div id="box" style="width:100px; height:30px; position:absolute"></div>
</body>

I only want the coordinates to be visible when the mouse pointer is hovering over the yellow rectangle. If I change <body onmousemove="showCoords(event)"> to <body>, the coordinates are never visible. How do I get the coordinates be visible only when hovering over the yellow rectangle?


Solution

Move the onmousemove listener from the body to the element you want to listen on - div.abs in this case.

I'd recommend not using the onmousemove attribute, in favour of using an entirely javascript solution - just to keep javascript-y things together. Something like (untested)

var listenOn = document.querySelector(".abs");
listenOn.addEventListener("mousemove", ShowCoords);


Answered By - Quasipickle
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.