Find Element’s Position using JavaScript

Tagged with: , , , , , , ,

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];
}

Original Article

13 Responses to “Find Element’s Position using JavaScript

  • 1
    Abdul Rhaman
    November 1st, 2007 15:39

    Hi Binny,

    It is really useful

    ragds,
    Abdul

  • 2
    no
    April 3rd, 2008 20:39

    doesn’t work.

  • 3
    Name
    June 12th, 2008 20:30

    This does not work. A demo would be nice.

  • 4
    karthik
    July 1st, 2008 11:30

    This is not working

  • 5
    vishnu
    September 26th, 2008 19:42

    This doesn’t work.

  • 6
    vishnu
    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];
    }

  • 7
    should site source
    October 10th, 2008 02:38

    code was stolen from (unless original author):
    http://www.quirksmode.org/js/findpos.html

  • 8
    Praveen
    December 23rd, 2008 11:23

    Hi ..
    The solution given by you is really nice and working properly in javascript. Thankyou..!!

  • 9
    Noradin
    February 5th, 2009 22:22

    works like charm :)

    very nice script!

  • 10
    Arif
    April 26th, 2009 17:32

    Thanks for the nice sol.
    @ vishnu : it works. please check you get the element object properly.

    Thanks

  • 11
    psiko
    April 30th, 2009 01:07

    thanks for that, this is a lifesaver!

  • 12
    Abhishek
    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.

  • 13
    Matthew
    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.

Leave a Reply