Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!