Get an element's position with Javascript
Posted March 16th, 2010 in Javascript
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);
Related posts:
- Get an element's position relative to the document with jQuery (Tuesday, February 9th 2010)
- jQuery: Mouse co-ordinates within the element when mouseover or click an element (Wednesday, October 28th 2009)
- Get the mouse co-ordinates with jQuery when an element is clicked (Friday, October 9th 2009)
- Get the mouse co-ordinates with jQuery (Tuesday, October 6th 2009)

Comments
blog comments powered by Disqus