Finding Elements Top and Left Using JavaScript

December 21, 2007

Recently,

I was trying to create orkut like interface, where user can click on image and upload files using IFrame, so it gave ajax like user experience.

For this I used javascript to find top, left, height and width of image so I could display iframe from center of image.

My javascript function was something like this

function ShowUploadFrame(myImage)

{

var frm = document.getElementById(‘ImageFrame’);
frm.src = “FileUpload.aspx”;

frm.style.display= “block”;

frm.style.top = parseInt(myImage.offsetTop) +
(parseInt(myImage.style.height)/2) + ‘px’;

frm.style.left = parseInt(myImage.offsetLeft) +
(parseInt(myImage.style.width)/2) + ‘px’;

}

I always use Mozilla Firefox(FF), so when I tested my code it worked perfectly.But, when I tested this code in Internet Explorer 6(IE6) the offsetTop did not work correctly.

I used Google my best friend to find the answer, and here is what I found

“When your element is nested inside other elements or when it has elements above it with position relative or absolute, element.offsetTop does not work properly in IE6.”

So, I found this code from different blogs on net

Now, my javascript function is as below

function ShowUploadFrame(myImage)

{

var frm = document.getElementById(‘ImageFrame’);
frm.src = “FileUpload.aspx”;
frm.style.display= “block”;

var dim = GetTopLeft(myImage);

frm.style.top = (parseInt(dim.Top) +
(parseInt(
myImage.style.height)/2)) + ‘px’;

frm.style.left = parseInt(dim.Left) +
(parseInt(myImage.style.width)/2) + ‘px’;

}

But the important function GetTopLeft(elm) is what you should have a look at, if you want to find Top and Left of element using Javascript.

function GetTopLeft(elm)

{

var x, y = 0;

//set x to elm’s offsetLeft
x = elm.offsetLeft;

//set y to elm’s offsetTop
y = elm.offsetTop;

//set elm to its offsetParent
elm = elm.offsetParent;

//use while loop to check if elm is null
// if not then add current elm’s offsetLeft to x
//offsetTop to y and set elm to its offsetParent

while(elm != null)
{

x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}

//here is interesting thing
//it return Object with two properties
//Top and Left

return {Top:y, Left: x};

}

Here are two important points I would like to share are

  1. I used while loop to find if elm has parent, then add the elements offsetLeft to x and offsetTop to y variable and set elm’s offsetParent to elm.
  2. I used return {Top:y, Left: x}; which returns an Object with two properties Top and Left whose values are set to y and x respectively.

That’s all folks.
Hope you enjoyed this post.

Comments Good as well as Bad are most welcome.

Advertisements