Alex Rivera | Logout

Getting offsetTop of element in a table

Asked 2009-06-25T16:47:43.970
10

I can't seem to figure out how to get the offsetTop of an element within a table. It works fine on elements outside tables, but all of the elements within a table return the same result, and it's usually at the top of the page. I tried this in Firefox and Chrome. How do I get the offsetTop of an element in a table?

Edit
Report

1 Answer

28

offsetTop returns a value relative to offsetParent; you need to loop through all of the parents adding offsetParent.offsetTop until offsetParent is null. Consider using jQuery's offset() method.

If you don't want to use jQuery, you can write a method like this (untested):

function offset(elem) {
    if(!elem) elem = this;

    var x = elem.offsetLeft;
    var y = elem.offsetTop;

    while (elem = elem.offsetParent) {
        x += elem.offsetLeft;
        y += elem.offsetTop;
    }

    return { left: x, top: y };
}
answered 2009-06-25T16:53:29.210

Your Answer