6/121

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

Might be useful