Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Get the relative position of the mouse when using `onmousemove` inside of the tag

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!