Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find offsetTop relative to parent, not window top?

My question is fairly straightforward: How can you find the offsetTop of a child element compared to it's parent element (rather than the window top)?

The definition of offsetTop states that the property will return the value by which a child element is offset from the top of an offsetParent, but this doesn't seem to be the case in this JSFiddle: http://jsfiddle.net/h5KBK/.

My goal is to find the offset of the bolded orange text from the top of the scrollable div, not the window top. Is there any way to do this without calculating the heights of the above elements, paddings, margins, etc. and subtracting it from the offsetTop?

I'm looking for a JavaScript only solution. No jQuery please.

like image 202
Shrey Gupta Avatar asked Jan 01 '13 03:01

Shrey Gupta


People also ask

How do you find the position of an element relative to a parent?

We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree.

How do you get an element's top position relative to the browser's viewport?

We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.

How is offsetTop calculated?

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 element of a Offset?

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.


2 Answers

By definition offsetTop returns the top position of the object relative to the top side of its offsetParent element, in pixels.

Now offsetParent needs to be an element with a position other than static. If you change the position attribute of scroll element in your fiddle I get a value of 1012 as opposed to 1110 without the position attribute.

like image 75
Ravi Y Avatar answered Oct 21 '22 01:10

Ravi Y


Actually, I did some more research and figured out the answer. The offsetParent must have a specified position:absolute or position:relative declaration, as shown in this JSFiddle: http://jsfiddle.net/h5KBK/1/

like image 3
Shrey Gupta Avatar answered Oct 21 '22 01:10

Shrey Gupta