I have basically 2 div elements. The first is a scrolling container and the second one is an element that is placed in the container. I would like to find the y-position relative to the scrolling container. I wrapped all of it into a piece of example-code titled How to find Mr. Blue?
<div style="height:100px; border:solid 1px black; overflow-y:scroll;">
Please scroll down...
<br/>
<div style="height:400px;">
</div>
<br/>
<div id="MrBlue" style="height:20px; background-color:blue; color:white">
Mr. Blue
</div>
</div>
So I would like a JavaScript / jQuery statement that alerts the vertical-position of the Mr. Blue. div relative to the scrolling container.
Ps. If you would like to 'fiddle' with mr. Blue, check http://jsfiddle.net/KeesCBakker/Qjr5q/.
To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element. Here is example: const div = document. querySelector('.
The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.
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.
jQuery position() Method The position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.
If you can add css position: relative
to the wrapping/scrolling container then it's as simple as
document.getElementById('MrBlue').offsetTop
and jsfiddle example http://jsfiddle.net/eU3pN/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With