Getting element position in IE versus other browsers

Posted by Channel72 on Stack Overflow See other posts from Stack Overflow or by Channel72
Published on 2010-04-11T13:19:36Z Indexed on 2010/04/11 13:23 UTC
Read the original article Hit count: 272

We all know IE6 is difficult. But there seems to be disparate behavior in positioning in later versions of IE as well, when compared with Firefox or other browsers. I have a simple pair of javascript functions which finds the position of an element, and then displays another element in relation to the first element. The idea is to get the second element, which is somewhat larger, to appear in front of the first element when the mouse hovers over it. It works fine, except on all versions of Internet Explorer, the position of the second element appears different than in Firefox.

The code to get the position of an element is:

function getPosition(e) 
{
    var left = 0;
    var top  = 0;

    while (e.offsetParent) {
        left += e.offsetLeft;
        top  += e.offsetTop;
        e = e.offsetParent;
    }

    left += e.offsetLeft;
    top += e.offsetTop;
    return {x:left, y:top};
}

And the actual rollover display code is:

var pos = getPosition(elem1);
elem2.style.top = pos.y - 8;
elem2.style.left = pos.x - 6;

In Firefox, elem2 appears directly over elem1, as I want it to. But in IE7 or IE8 it appears way off. What is the reason this occurs, and is there a way to fix it?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about internet-explorer