/html-dom /Basic
GitHub 4932★

Calculate the mouse position relative to an element

The following code calculates the mouse position relative to the clicked element:

ele.addEventListener('mousedown', function (e) {
// Get the target
const target = e.target;

// Get the bounding rectangle of target
const rect = target.getBoundingClientRect();

// Mouse position
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
});

Use case

See also

Follow me on and to get more useful contents.