0

If I have a nested HTML element called Div1 (a div that sits inside another div & that other div sits inside the body), how can I get Div1's x,y position from the body elements perspective maybe this is called window/screen position of a HTML element)?

Hope this makes sense :)

Wayne
  • 59,728
  • 15
  • 131
  • 126
Mack
  • 335
  • 2
  • 4
  • 14
  • See: http://stackoverflow.com/questions/442404/dynamically-retrieve-html-element-x-y-position-with-javascript – BStruthers Mar 23 '11 at 01:46

2 Answers2

3
function getWhere(node, top){
    top= top || document.body;
    var x= 0, y= 0;
    while(node){
        y+= node.offsetTop;
        x+= node.offsetLeft;
        node= node.offsetParent;
        if(node== top) break;
    }
    return [x, y];
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

If you're using jQuery you can use offset to get the position relative to the document.

$(element).offset();

See: http://api.jquery.com/offset

Unfortunately I have no idea how to do this with pure js.

Mark Brown
  • 12,026
  • 8
  • 27
  • 32
  • Do the downvoter: I realize, the OP's question didn't specifically mention jQuery, but how is this not a valid suggestion? – Mark Brown Mar 23 '11 at 02:37
  • Because it can be regarded as proselytizing. I personally do not care when a jQuery answer is posted on a non-jQuery question, but a certain percentage of SO users will react negatively to it. – Šime Vidas Mar 23 '11 at 03:30