views:

528

answers:

2

Hello, 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?

thanks!

A: 

offsetTop returns the position relative to the offsetParent, not the window. For your table elements, the offsetParent is the table.

You could fix this by following the offsetParent tree and accumulating the offsets, I suppose, or you could just use jQuery and do $(element).offset().

chaos
+2  A: 

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

EDIT: 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 };
}
SLaks