Rella Rella - 19 days ago 5
HTML Question

How to get top left corner of tag not using JQuery?

How to get top left corner of tag not using JQuery?

Answer

element.offsetLeft and element.offsetTop will get you the top let corner relevant to its parent

function top(el) {
    var topVal = el.offsetTop;
    if (el.parentNode) topVal+= top(el.parentNode);
    return topVal;
}

function left(el) {
    var leftVal = el.offsetLeft;
    if (el.parentNode) leftVal+= left(el.parentNode);
    return leftVal;
}

calling it recursively up until you hit the documment (document.parentNode is null and ends rescursion) will get you it relative to the entire document. Be wary that this isn't compatible with iframe or anything else that has its own document.

[Edit]

The above recursive function is far too naive and only works on very simple pages. You can iterate over offsetParent instead but that also causes some issues.

This solution seems to work reasonably, but I havnt tested it thoroughly myself

Dynamically retrieve Html element (X,Y) position with JavaScript