codesandbox example here: https://codesandbox.io/s/quirky-wozniak-3qih8p?file=/src/Progress.tsx
I am trying to use the Intersection Observer API to track both the first and last elements of my list. My goal is to display either a left or right button based on the horizontal scroll position.
However, I have run into an issue where the intersection observer is only tracking the first element and I am unsure why this is happening and how to correct it.
3
Answers
This might be because you are observing the left and right arrow with same intersection observer instance. One possible fix can be making two separate instances for both arrows.
From the docs, the IntersectionObserver callback is called with:
So, you do not necessarily receive both
[first, last]
elements in the callback – just those whose amount of intersection has changed.As a rough cut you might use something like:
Sandbox
A solution without IntersectionObserver:
You may want to throttle the
onScroll
function of course.See example