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

154
Vistas
Intersection Observer: Remove class when element scrolls out of view

I have a couple of anchor links that scroll to content cards:

  <nav class="bg-light p-4 d-flex justify-content-between">
    <div class="anchor-buttons">
      <a href="#c1" class="btn btn-outline-primary">Content 1</a>
      <a href="#c2" class="btn btn-outline-primary">Content 2</a>
    </div>
  </nav>
  <section class="p-5">
    <div class="card my-5 p-5" id="c1">Content 1</div>
    <div class="card my-5 p-5" id="c2">Content 2</div>
  </section>

The card that has been navigated to, is being highlighted by giving it an active class:

  function highlightCard() {
    $(".anchor-buttons a").on("click", function () {
      var id = $(this).attr("href");
      $(".active").removeClass("active"); // remove existing active
      $(id).addClass("active"); // set current link as active

      observeCard();
    });
  }

Next, I want to remove the class, when the element is scrolled out of the viewport.

I tried to use this code, but can't figure out how to connect it to the other function. When the target card is not in view, the intersection observer removes it right after it has been added via click.

  function observeCard() {
    const el = document.querySelector(".active");
    const observer = new window.IntersectionObserver(
      ([entry]) => {
        console.log(entry.boundingClientRect.top);
        if (entry.isIntersecting) {
          console.log("Enter");
          return;
        }
        console.log("Leave");
        $(".active").removeClass("active");
        if (entry.boundingClientRect.top > 0) {
          // do things if below
        } else {
          // do things if above
        }
      },
      {
        root: null,
        threshold: 0
      }
    );

    observer.observe(el);
  }

Sandbox: https://codesandbox.io/s/long-platform-30qjk?file=/index.html:2095-2109

Thanks for any pointers!

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