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

155
Visualizações
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 à 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