Get abs pos of dom element

2012-05-13 20:20:11

This is a very very (VERY) simple approach to getting the absolute position of a element in the current dom. Nothing fancy here, just needed it and couldn't find it in my (these) notes for fast copy-pasting... :)

Note that this doesn't take scrolling into account. It's also not very cross-(old)browser or whatever.

Code:
function abspos(e){
var x = e.offsetLeft + (e.clientLeft|0);
var y = e.offsetTop + (e.clientTop|0);
while ((e = e.offsetParent) && e.nodeName != 'BODY') {
x += e.offsetLeft + (e.clientLeft|0);
y += e.offsetTop + (e.clientTop|0);
}
return [x,y];
};

offset* doesn't seem to include the border, which is put in the client*, but not in every browser. Sigh. So if you want the top-left coorindate inside the border, leave out the client* values, but only for the last element (of course), which is the initial setting of x and y so that'd be a simple change.

I might amend the scrolling bits later, otherwise consider it an exercise for the reader. Note: that's you! ;)

Hope it helps you.