Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting left and top offset for body element with margin:auto

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!

like image 758
gaspercat Avatar asked Apr 30 '12 12:04

gaspercat


1 Answers

Use element.getBoundingClientRect() to get the relative offsets of an element:

var bodyOffsets = document.body.getBoundingClientRect();
//bodyOffsets.top   ;
//bodyOffsets.left  ;
like image 195
Rob W Avatar answered Oct 26 '22 05:10

Rob W