Email This Post Email This Post Print This Post Print This Post

Finding the Position of an object

Tue, Oct 9, 2007 – 4:25 am

There are many times when you need to use JavaScript to find the current position of an object on the screen.

The object properties offsetTop and offsetLeft give the position of the object in terms of how far it is offset. The problem is that it is not how far you are offset from the top and left of the screen. It is how far you are offset from the table or element (the Parent) which contains your object.

Knowing that your object is 30 pixels down from the top of a table does you absolutely no good if the table is located at the bottom of the screen.

This means that instead of being able to refer to the object properties offsetTop and offsetLeft to get it’s current location you have to also find the values of offsetTop and offsetLeft of it’s parent.

It’s only after adding all the offsets together will you get the coordinates your need.

Below is function which will do this for you.

// Figure out where the obj object is on the screen by adding
// up all the offsets for all the containing parent objects

function FindPosition(obj) {

 // Assign the obj object to a temp variable
 tmpObj = obj;

 // Get the offsets for the current object
 var obj_left = tmpObj.offsetLeft;
 var obj_top = tmpObj.offsetTop;

 // If the current object has a parent (ie contained in a table, div, etc..)
 if (tmpObj.offsetParent) {

  // Loop through all the parents and add up their offsets
  // The while loop will end when no more parents exist and a null is returned
  while (tmpObj = tmpObj.offsetParent) {
   obj_left += tmpObj.offsetLeft;
   obj_top += tmpObj.offsetTop;
  }
 }
 return [obj_left , obj_top];
}

The following script illustrates how it would be used:

// Get reference to element which has the ID of "Home"
var MenuItem = document.getElementById("Home");

// Find current position of the MenuItem object
var curr_pos = FindPosition(MenuItem);
var curr_left = curr_pos[0];
var curr_top = curr_pos[1];
  1. 3 Responses to “Finding the Position of an object”

  2. You saved me!!! I have been fighting agains the position bugs from the different browsers and nothing seemed to work. Thanks to your function I made it work.

    Thank you so much!!

    By Lucrecia on Dec 28, 2007

  3. Glad to help.

    The fact that no built in method or property exists for this has always baffled me.

    By Stan Slaughter on Jan 1, 2008

  1. 1 Trackback(s)

  2. Oct 17, 2007: StanSight » Blog Archive » Tooltips for Forms

Post a Comment