15 thoughts on “Find Element’s Position using JavaScript

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

  2. 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.

  3. 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;

Leave a Reply

Your email address will not be published. Required fields are marked *