user3932611
user3932611

Reputation:

Javascript get absolute position of a div

I have a div (oCell) created at runtime using javascript.

I then want to position another independant div (random-div) relative to this div. For reasons within the program random-div has to be positioned absolutely and oCell relatively. The oCell div is positioned relative as it is within a table.

My problem is I need to find the absolute position of the oCell div, rather than the relative position.

So far I have:

var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right; 

But from what I can understand, this is returning the relative height of oCell div, which is in turn not positioning random-div in the correct place.

Upvotes: 2

Views: 2755

Answers (1)

Patrick
Patrick

Reputation: 6948

The getBoundingClientRect gives coordinates in viewport coordinates (or coordinates relative to the visible content shown in your browser window). With absolute positioning, you need document coordinates. To convert viewport coordinates to document coordinates, add the scroll offsets of the page to the left and top values returned by getBoundingClientRect:

//technique used in JavaScript: Definitive Guide
var scrollOffsets = (function () {
    var w = window;

    // This works for all browsers except IE versions 8 and before
    if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
    // For IE (or any browser) in Standards mode
    var d = w.document;
    if (document.compatMode == "CSS1Compat")
    return {x:d.documentElement.scrollLeft, y:d.documentElement.scrollTop};
    // For browsers in Quirks mode
    return { x: d.body.scrollLeft, y: d.body.scrollTop };
}());

//Your code:
var oCell = document.createElement("td");
//changed from height to top and gets document coordinates of position
var top = oCell.getBoundingClientRect().top + scrollOffsets.y;
//changed from right to left
var left = oCell.getBoundingClientRect().left + scrollOffsets.x;
oCell.oBoxPositionTop = top;
oCell.oBoxPositionSide = left;

Upvotes: 3

Related Questions