Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why an intersection observer doesn't observe the second element?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the docs, the IntersectionObserver callback is called with:

entries
An array of IntersectionObserverEntry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.

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:

    const observer = new IntersectionObserver(
      entries => {
        const lookup = new Map(entries.map(entry => [entry.target, entry.isIntersecting]));
        setLeftVisible(!lookup.get(leftRef.current!));
        setRightVisible(!lookup.get(rightRef.current!));
      },
      ...
    );

Sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading