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];
}
Hi Binny,
It is really useful
ragds,
Abdul
doesn’t work.
This does not work. A demo would be nice.
This is not working
This doesn’t work.
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];
}
code was stolen from (unless original author):
http://www.quirksmode.org/js/findpos.html
Hi ..
The solution given by you is really nice and working properly in javascript. Thankyou..!!
works like charm 🙂
very nice script!
Thanks for the nice sol.
@ vishnu : it works. please check you get the element object properly.
Thanks
thanks for that, this is a lifesaver!
It will not work if your web page is having scroll and control becomes visible when you scroll ur web page.
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.
not working? try onclick=”findPos(this)” on ur object. 100% it will work
The above script does not work if your page contents are centred using css such as ‘margin: 0 auto;’. The offsetLeft value will be off by the left hand margin of the high level container at the time the code is executed. Get the offsetLeft value of the hign level container and subtract this from the answer given by the code above.
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while (obj) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
}
// reduce left offset by margin caused by auto centre
var obj = document.getElementById(‘container’);
curleft -= obj.offsetLeft;