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
- Attach or detach an event handler
- Drag and drop element in a list
- Drag and drop table column
- Drag and drop table row
- Drag to scroll
- Get the position of an element relative to another
- Get the position of an element relative to the document
- Make a draggable element
- Show a custom context menu at clicked position
- Show or hide table columns