Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda