Last month I posted how to get an element’s position relative to the document with jQuery and in this post show how to do the same thing but with native Javascript without the use of a 3rd party library.
Working example
The text below starts of saying "The offset co-ordinates are …" and then the Javascript code replaces the … with the actual co-ordinates. If you are reading this in a feed reader it will not work and you will need to click through to view this in a web browser.
The offset co-ordinates are …
Getting the co-ordinates
The following function returns the co-ordinates for the element with the id passed in as a string:
function getElementTopLeft(id) { var ele = document.getElementById(id); var top = 0; var left = 0; while(ele.tagName != "BODY") { top += ele.offsetTop; left += ele.offsetLeft; ele = ele.offsetParent; } return { top: top, left: left }; }
To get the co-ordinates of the following div:
<div id="mydiv"></div>
Do this:
var TopLeft = getElementTopLeft("mydiv");
To use the values in an alert box for example, do this:
alert(TopLeft.top + ', ' + TopLeft.left);