0

I have a simple structure div named scrollContainer with overflow-y:scroll rule and an inner larger div called inner.

In the inner div I have some texts and an input. On the input I have an attribute directive called getPosition applied, which should return on scroll event the exact position of the input relative to the top of scrollContainer.

This is what I need: enter image description here

Here is the sample angular app: https://codepen.io/neptune01/pen/vapmLQ

As you can see, tried with offsetTop and other dom properties, but I couldn't find anything that would result what I need.

1 Answer 1

2

I would recommend using a combination of getBoundingClientRect() and the current scroll position to accomplish this like so:

let outer = document.getElementById('scrollContainer');
let inner = document.getElementById('inner');

let outerTop = outer.getBoundingClientRect().top + (window.scrollY || window.pageYOffset);
let innerTop = inner.getBoundingClientRect().top + (window.scrollY || window.pageYOffset);

let difference = innerTop - outerTop;

The reason you wouldn't just subtract outer top from inner top in the first place and ignore the scroll position is because on the off chance that you are scrolling while the calculations take place you could throw off the offset, as getBoundingClientRect() only takes into account the distance from the edge of your view to the element, while the scrollY shows the distance from the edge of your view to the top of the document.

Sign up to request clarification or add additional context in comments.

1 Comment

$(element[0]).offset().top to OP if you are ever going to use jquery library. But this is the correct solution in vanilla js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.