I'm trying to get the mouse position relative to the body (that is, body = coordinates origin) for a website which has it's body element fixed in size and centered by using the margin:auto CSS attribute.
Since the event.clientX and event.clientY attributes give me the offset from the beginning of the page, not from the body element, I've tried to substract it the body offset. To do so, I've tried to use document.body.offsetLeft & document.body.offsetTop, but no luck so far, the value is undefined. Also, since I didn't define it, I can't use document.body.style.left or document.body.style.top.
Does anybody know a way to get the body offset OR directly get the mouse coordinates relative to a DOM element?
Thank you in advance!
Use element.getBoundingClientRect()
to get the relative offsets of an element:
var bodyOffsets = document.body.getBoundingClientRect();
//bodyOffsets.top ;
//bodyOffsets.left ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With