Finding Elements Top and Left Using JavaScript

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

19 Responses to Finding Elements Top and Left Using JavaScript

  1. Afzaal says:

    I applied your code, but did not get desired results.
    Infect the situation I am using is as follows:

    I want to know top and left of a div holds and image and nested in two other divs.
    structure is like

    i passed ID of div product_image, but when i echo offsetParent, it doesn’t show value and says “undefined”.

    Can you please help me in this regard?

    Thank You
    Regards
    Afzaal

  2. Thomas says:

    I, on the other hand, applied your code and got exactly what I was looking for. 🙂
    Thanks!

  3. […] Vishal Astik has a great post on setting “top” and “left” on an element usin…. As with most things Javascript, nowadays, the problem is making it work in IE6. His key point is this: 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. […]

  4. OmPrakash says:

    Thanks a ton buddy. Solved my problem

  5. Alberto Lepe says:

    Thank you for sharing it.

    I think you have a small mistake at your ShowUploadFrame() function:

    parseInt(img.style.height)/2

    img is not previously defined, it should be: myImage, right?
    Also, myImage.style.height, at least in FF should be: myImage.height, otherwise return null.

    • Vishal says:

      @Alberto
      I have updated code as per your comment
      and I have specified height in Image tag so myImage.style.height works perfectly in IE 7 and 8 and Firefox 3.0.x

  6. stuart says:

    if you are wanting to know the correct position on the screen then you need to incorporate scrollTop, scrollLeft in case you have had to scroll down / accross otherwise the position will not be correct.

    for example
    y += obj.offsetTop – obj.scrollTop

    this is required if you want to put some popup for example calendar selector next to the field you have clicked.

  7. Vincent says:

    Hello Hi,

    and Thanks for sharing used your tactics and i got the desired results saved me some thanks.

  8. compton says:

    I would to the general hopscotch English comments a little note add make! For you, to I must say thankings muchings, the script of Java has much tribulations from me devolved 🙂

    Coop up the good work!

  9. zulu says:

    nice one,helpfull

  10. Jack says:

    I am trying to add listeners to a page where multiple iframes and divs load in a mix. Is there a way to iterate through all of them and add events to each possible open frame/child div?

  11. James says:

    @Jack : Use event delegation, instead of looping through all of those divs / iframes put the event above all of them ( say on the body ), then use your function to filter for the information you want ( i.e. if e.currentTarget.nodeName === ‘div’ || e.currentTarget.nodeName === ‘iframe’ ) hopefully you are using a library of some kind ( or one you created ) that normalizes e.currentTarget to refer to the element on which the event took place, and NOT the window element as Internet Explorer seems to insist it occurred on.

    Good reference for even delegation : http://cherny.com/webdev/70/javascript-event-delegation-and-event-hanlders

    Hope that helps

  12. prashant chalise says:

    This was really helpful for me. Thank you.

  13. Miguel says:

    Pardon for my English.
    I have tried function GetTopLeft in my code and works perfectly.
    Before, my code only was working on Firefox.
    Thank you from Spain!

  14. premson says:

    Just great!!!! thanks.

    I was having an issue by using jquery “this.offsetTop”, when my object is within nested components. this solved my issue.

  15. find me says:

    you can use :
    //set x to elm’s offsetLeft
    x = elm.cumulativeOffset().left;

    //set y to elm’s offsetTop
    y = elm.cumulativeOffset().top;

  16. Dominic Pascasio says:

    Exactly what I was looking for. Thank’s! Also, I like your saying,“KNOWLEDGE IS A WEALTH WHICH MULTIPLIES WHEN YOU SHARE IT”.

  17. I’m a newbie, can you help me use the GetTopLeft() function into asp.net/c# application, please? What I would like to know is how to call this function and store top & left properties into a local variable.

  18. greg says:

    This is a neat forceful work-around:

    var object = ______;
    var yourNumber = _____;
    object.style.top = parseInt(object.style.top.match(/-*\d+/)[0]) + yourNumber + ‘px’;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: