views:

550

answers:

2

I have a group DIV tags in an HTML page whose location is controlled via several parent/grandparent DIVs. Those parent and grandparent's location is controlled via CSS classes. I need to retrieve the top attribute of the given DIV. Where is it in the DOM or how would I calculate it using Javascript?


Clarification: I need the coordinate value of the top of the DIV object in absolute terms (relative to the window).

A: 

This would give you the top and left:

myDiv.offsetY
myDiv.offsetX
Mr. Smith
No it doesn't. Did you mean `offsetLeft`/`offsetRight`?
Crescent Fresh
Both offsetY and offsetX are undefined.
dacracot
@crescentfresh... offsetLeft is a relative value, not absolute (which I need) and offsetRight is undefined.
dacracot
+1  A: 

Since offsetTop and offsetLeft give you relative position values, you can get the absolute values by traversing up the tree of offsetParents, aggregating the offsetTop and offsetLeft values of each parent element:

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft,curtop];
  }
}

More detailed information: JavaScript Find position

CMS
I found this too. It is almost what I need. Is there any way to take into account scrolling? Not just window scrolling (window.scrollY) but also DIVs with scroll:auto attributes?
dacracot