Javascript - Element Position

What is the purpose of element.offsetTop?

The offsetTop property returns the number of pixels that the element is offset from the top edge of its offsetParent (the parent element that has position:relative, position:absolute, position:fixed, but not position:static). Effectively, this gives the element's position relative to its offset parent.

How can I determine the offset parent of an element?

Obviously, use element.offsetParent

If our calculation is not correct, what should we look into?

  • Tally up the margin, border, and padding of all offset parents.

Function to obtain the element position:

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }
    return { x: xPosition, y: yPosition };
}

The above code is taken from http://www.kirupa.com/html5/get_element_position_using_javascript.htm. Given an element, the above code all offset parent elements. The loop ends when there are no more parents.

The offsetTop and offsetLeft account for margins, paddings, and top/left values. The one value the offset properties don't take into account is an element's border. The reason is that the border is considered a part of an inner element's top-left corner, but its size does have an effect on the position of something. To measure the border size, we use the clientLeft and clientTop properties

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License