11 December 2010

Find position Javascript

On this page I give the necessary code to find out where an element is on the page. This script finds the real position, so if you resize the page and run the script again, it points to the correct new position of the element.

offset
In all browsers it's necessary to use the offsetTop and offsetLeft of the element. These properties give the coordinates relative to the offsetParent of the element.
The script moves up the tree of offsetParents and adds the offsetTop and offsetLeft of each. Eventually, regardless of the actual composition of the offsetParent tree, this leads to the real coordinates of the element on the screen.

JavaScript code.
The script is very simple. Hand it the object whose position should be calculated and set the variables curleft and curtop to 0:
function findPosY(obj) {
  var curtop = 0;
   if (obj.offsetParent)
     while (1) {
      curtop += obj.offsetTop;
      if (!obj.offsetParent)
         break;
         obj = obj.offsetParent;
      }
      else if (obj.y)
      curtop += obj.y;
     return curtop;
}
function findPosX(obj) {
  var curleft = 0;
   if (obj.offsetParent)
    while (1) {
     curleft += obj.offsetLeft;
     if (!obj.offsetParent)
         break;
      obj = obj.offsetParent;
      }
      else if (obj.x)
      curleft += obj.x;
      return curleft;
}
Now assign it to control.In my case it is a div panel. 
var positioY = findPosY(obj);
var positionX = findPosX(obj);
var curtop = 0;
div.style.top = positioY + "px";
div.style.left = (positionX + 10) + "px";