[thelist] Getting position with Javascript without setting them in Javascript

David Kaufman david at gigawatt.com
Sat Sep 24 22:18:48 CDT 2005

Hi Steve,

Steve James <steve at epicunion.com> wrote:
> [...] I need to use Javascript to get positions of
> DIVs on the page

Lifted (and tisted) from the most excellent Prototype library, written 
by Sam Stephenson, and available from http://conio.net/:

    function cumulativeOffset(element) {
      var valueT = 0, valueL = 0;
      do {
        valueT += element.offsetTop  || 0;
        valueL += element.offsetLeft || 0;
        element = element.offsetParent;
      } while (element);
      return [valueL, valueT];

as you can see, this recursively adds up the element's relative X and y 
offsets from it's parent, and the parent's in turn, from it's 
parentarent, and so on into antiquity, until it reaches the root node of 
the DOM (or Adam or Eve).  Works well for me and browser support for 
this technique seems to be excellent.



More information about the thelist mailing list