views:

333

answers:

2

I want to get an object's absolute x,y position on the page in Javascript. How can I do this?

I tried obj.offsetTop and obj.offsetLeft, but those only give the position relative to the parent element. I guess I could loop through and add the parent's offset, and its parent's offset, and so on until I get to the object with no parent, but it seems like there should be a better way. But Googling didn't turn up much, and even SO site search isn't finding anything.

Also, I can't use jQuery.

+5  A: 
var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

eyelidlessness
A: 

You will get a different value in each browser FireFox and IE when you are using offsetTop and offsetLeft. I think it makes you don't waste your time like I do.

gacon