0

Consider the code below. This code returns the absolute position of the mouse when hovering over the div tag.

<!DOCTYPE html>
<html>
<head>
<style>
div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}
</style>
</head>
<body>

<p>This example demonstrates how to assign an "onmousemove" event to a div element.</p>

<div onmousemove="myFunction(event)"></div>

<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>

<p id="demo"></p>

<script>
function myFunction(e) {
  var x = e.clientX;
  var y = e.clientY;
  var coor = "Coordinates: (" + x + "," + y + ")";
  document.getElementById("demo").innerHTML = coor;
}
</script>

</body>
</html>

Now, I'd like to use div.offsetLeft inside the function in order to calculate the relative mouse position. The problem is, if I try doing something like:

<script>
function myFunction(e) {
  var x = e.clientX - this.offsetLeft;
  var y = e.clientY - this.offsetHeight;
  var coor = "Coordinates: (" + x + "," + y + ")";
  document.getElementById("demo").innerHTML = coor;
}
</script>

I get an error. The this is not referencing the div tag, but something else... Any ideas on how to solve this?

Davi Barreira
  • 1,437
  • 8
  • 17
  • Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Yogi May 08 '22 at 15:38

0 Answers0