0

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).

2
  • Dup: stackoverflow.com/questions/610188/… Commented Sep 1, 2009 at 20:24
  • Yep... It is a duplicate. I voted to close also. I didn't just delete it since someone else might not find the other question through searching (aka the same problem I had). Commented Sep 1, 2009 at 20:36

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

This would give you the top and left:

myDiv.offsetY
myDiv.offsetX

3 Comments

No it doesn't. Did you mean offsetLeft/offsetRight?
Both offsetY and offsetX are undefined.
@crescentfresh... offsetLeft is a relative value, not absolute (which I need) and offsetRight is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.