<main>
  <div class="container">
    <section id="s-1"></section>
    <section id="s-2"></section>
    <section id="s-3"></section>
    <section id="s-4"></section>

  </div>
  <div class="scroll-nav">
    <nav>
      <a href="#s-1">S1</a>
      <a href="#s-2">S2</a>
      <a href="#s-3">S3</a>
      <a href="#s-4">S4</a>
    </nav>
  </div>
</main>
html {
  scroll-behavior: smooth;
  font-family: sans-serif;
}

html,
body {
  padding: 0;
  margin: 0;
}

.scroll-nav {
  position: fixed;
  top: 0;
  left: 0;
  padding: 1rem;
  margin-left: 1rem;
  margin-top: 1rem;
  background: #eaeaea;
  border-radius: 1rem;
  box-shadow: 0 8px 16px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #dfdfdf;
}

.scroll-nav a {
  text-decoration: none;
  color: #1d1d1f;
  padding: 0.25rem;
  background: #aaa;
  color: #fff;
  border-radius: 0.25rem;
}

.scroll-nav a.active {
  background: #0059a6;
}

section {
  width: 100%;
  height: 500px;
}

section:nth-child(1) {
  background: #cffafe;
}

section:nth-child(2) {
  background: #a7f3d0;
}

section:nth-child(3) {
  background: #d9f99d;
}

section:nth-child(4) {
  background: #fef08a;
}
document.addEventListener("DOMContentLoaded", function () {
  function addClassOnScrollToSection(
    sectionId,
    className,
    targetElementSelector
  ) {
    const targetSection = document.getElementById(sectionId);
    const targetElement = document.querySelector(targetElementSelector);

    if (!targetSection || !targetElement) {
      retur;
    }

    function checkScrollPosition() {
      const scrollPosition = window.scrollY + window.innerHeight / 2; // Middle of the viewport
      const sectionTop = targetSection.offsetTop;
      const sectionBottom = sectionTop + targetSection.offsetHeight;

      if (scrollPosition >= sectionTop && scrollPosition < sectionBottom) {
        targetElement.classList.add(className);
      } else {
        targetElement.classList.remove(className);
      }

      console.log("scrollPosition", scrollPosition);
      console.log("sectionTop", sectionTop);
      console.log("sectionBottom", sectionBottom);
    }

    window.addEventListener("scroll", function () {
      checkScrollPosition();
    });

    checkScrollPosition();
  }

  const sections = ["s-1", "s-2", "s-3", "s-4"];
  sections.forEach(function (elem) {
    addClassOnScrollToSection(elem, "active", `a[href='#${elem}']`);
  });
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.