For more tips like this, sign up to the weekly newsletter!

Get an event's coordinates relative to an element

The MouseEvent object has several properties that indicate the position where the event happened. The primary distinction between them is the coordinate system they use:

  • offsetX/Y have the coordinates relative to the target element
  • pageX/Y are to the document
  • screenX/Y are to the screen
  • clientX/Y (aka. x/y) are to the viewport
Get the coordinates relative to another element

But how to get the coordinates relative to another element?

The key is to get the element's coordinates in the same coordinate system as the event position. The simplest solution is to use .getBoundingClientRect() which uses viewport coordinates, the same as clientX/Y.

const {top, left} = element.getBoundingClientRect();

const eventTop = event.clientY - top;
const eventLeft = event.clientX - left;
Try it
References
Learn more: