Reputation: 1223
I have a scroll container where children are scrolling in vertical direction. It has many small elements. The height of my scroll container is 100vh. My task is to observe them as soon as they reach 100px below top border(which is top of viewport in my case).
To achieve this I am creating an intersection observer on my scroll container element with rootmargin as -100px 0px 0px 0px
.
I am observing on threshold 1.
In the intersection observer callback I am checking: entry.intersectionRect.top === entry.rootBound.top
. This ensures that I am checking only topmost element.
All these operations are happening as expected but with one problem: intersection is not being observed 100px below top, but 81px below top. I confirmed this when I checked that in callback, value of entry.rootBound.top is 81px.
I suppose this should not be the case, the rootBound should have top similar to top margin that I gave in constructor option.
Very new to intersection observer and I want to use it in my project, but cannot do so with inconsistencies.
Upvotes: 1
Views: 1988
Reputation: 1223
The only possible solution that seemed to be working correctly to me is to put an intersection observer on whole viewport, but pass a top margin of 10px(could be any value). Then observe that when the page loads, we would get a rootBounds
value and that could indicate what is rootBounds.top
. From there we could infer what is the device pixel ratio(givenMargin/rootBounds.top
). Then we can simply unobserve that Infinite intersection observer.
This works generic for any browser, without worrying about to check which browser are we working on. Or we could check for browser and it's version and then import this kind of utility in our code.
Upvotes: 0