Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting offsetTop of element in a table

I can't seem to figure out how to get the offsetTop of an element within a table. It works fine on elements outside tables, but all of the elements within a table return the same result, and it's usually at the top of the page. I tried this in Firefox and Chrome. How do I get the offsetTop of an element in a table?

like image 494
Matthew Avatar asked Jun 25 '09 16:06

Matthew


People also ask

How is offsetTop calculated?

The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.

How do I get Offsetbottom?

In the above code, the “div” element is created for which the offset bottom is calculating once the button is clicked. The offset bottom is calculating by using this statement “var bottom = el. offsetTop + $(el). outerHeight();” and calculated value is displaying by the alert, as we can see in the output.

What does offsetTop mean?

The HTMLElement. offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent , the closest positioned ancestor element.

How do you find the top position of an element?

$("#myTable"). offset(). top; This will give you the computed offset (relative to document) of any object.


1 Answers

offsetTop returns a value relative to offsetParent; you need to recursively add offsetParent.offsetTop through all of the parents until offsetParent is null. Consider using jQuery's offset() method.

EDIT: If you don't want to use jQuery, you can write a method like this (untested):

function offset(elem) {
    if(!elem) elem = this;

    var x = elem.offsetLeft;
    var y = elem.offsetTop;

    while (elem = elem.offsetParent) {
        x += elem.offsetLeft;
        y += elem.offsetTop;
    }

    return { left: x, top: y };
}
like image 75
SLaks Avatar answered Oct 21 '22 17:10

SLaks