Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect distance of HTML element from to top and to left?

I have a tag within a HTML5 document.

How can I detect the distance with JavaScript from the top-left corner of the HTML page to the top left corner of the canvas tag?

I need to be able to position dynamically generated html tags relative to the canvas.

like image 836
John R Avatar asked Sep 30 '11 13:09

John R


1 Answers

getBoundingClientRect() is your friend and is supported in recent-ish versions (Firefox 3, Safari 4, Chrome, Opera 9.5, IE 5) of all browsers. It will give you coordinates relative to the viewport rather than the page, however, so you need to add on the document's scroll amounts:

function getPageTopLeft(el) {
    var rect = el.getBoundingClientRect();
    var docEl = document.documentElement;
    return {
        left: rect.left + (window.pageXOffset || docEl.scrollLeft || 0),
        top: rect.top + (window.pageYOffset || docEl.scrollTop || 0)
    };
}
like image 161
Tim Down Avatar answered Oct 21 '22 12:10

Tim Down