Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
Targeting the nearest intersection to the root when multiple items are intersecting

I have a list of sections inside of a container (root), each one observed by the same Intersection Observer.

When clicking an anchor on the left-nav (red), it scrolls to that section and the intersection observer callback updates the state with the correspondent section ID. In short, I'm trying to dynamically style the anchor while scrolling and navigating recording the ID and comparing it to the href attribute.

It works as expected as long as only one section respects the threshold, but sometimes I face this situation:

Targeting the nearest intersection to the root when multiple items are intersecting

When scrolling to top (e.g. from 4 clicking to 2), it works as expected, the last state ID corresponds to the href attribute I just clicked.

But when I scroll down (e.g. from 1 clicking to 2), since 2, 3 and 4 are visible, the last section ID set in the state corresponds to the section #4.

Is there any way to target always the nearest entry to the root?

export const Main = () => {
  const sectionRefs = useRef([]);
  const observerRef = useRef(null);

  const [intersectionId, setIntersectionId] = useIntersection();

  useEffect(() => {
      const intersectionCallback = (entries) => {
        entries.some((entry) => {
          if (entry.isIntersecting) {
            setIntersectionId(entry.target.id);
            return true;
          }
        });
      };

      observerRef.current = new IntersectionObserver(intersectionCallback, {
        root: document.getElementById('root'),
        threshold: 0.75,
        rootMargin: '0px 0px 0px 0px',
      });

      examplesRefs.current.forEach((sectionElement) => {
        observerRef.current.observe(sectionElement);
      });

      return () => {
        observerRef.current.disconnect();
      };
  }, [setIntersectionId]);

  return (
    <Container id="root">
      {examples.map(({ id }, index) => (
        <Section
          key={id}
          id={id}
          ref={(child) => (sectionRefs.current[index] = child)}
        />
      ))}
    </Container>
  );
};
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda