Find Element’s Position using JavaScript
Tagged with: coordinates, dom, element, JavaScript, js, offset, position, xy
Find the position of an element using javascript
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
Follow me(@binnyva) on Twitter
November 1st, 2007 15:39
Hi Binny,
It is really useful
ragds,
Abdul
April 3rd, 2008 20:39
doesn’t work.
June 12th, 2008 20:30
This does not work. A demo would be nice.
July 1st, 2008 11:30
This is not working
September 26th, 2008 19:42
This doesn’t work.
September 26th, 2008 19:44
u r code not working, i tried like this ,
this is working in IE but Firfox3 is not working
function findPosition(id)
{
var off=document.getElementById(id)
if (off.offsetParent) {
curleft = off.offsetLeft;
curtop = off.offsetTop;
while (off) {
curleft += off.offsetLeft;
curtop += off.offsetTop;
off=off.offsetParent;
}
}
return [curleft,curtop];
}
October 10th, 2008 02:38
code was stolen from (unless original author):
http://www.quirksmode.org/js/findpos.html
December 23rd, 2008 11:23
Hi ..
The solution given by you is really nice and working properly in javascript. Thankyou..!!
February 5th, 2009 22:22
works like charm
very nice script!
April 26th, 2009 17:32
Thanks for the nice sol.
@ vishnu : it works. please check you get the element object properly.
Thanks
April 30th, 2009 01:07
thanks for that, this is a lifesaver!
July 22nd, 2009 16:47
It will not work if your web page is having scroll and control becomes visible when you scroll ur web page.
September 16th, 2009 06:21
It could be more straightforward to write the code like this:
function findPosSimpler(obj) {
var curleft = curtop = 0;
while (obj) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
obj = obj.offsetParent
}
return [curleft,curtop];
}
The first `if’ in the original is already taken care of by the `while’, and there’s no error-prone assignment `=’ embedded in the loop condition.