Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda