インジケーター

Javascript

HTML

<div id='indicator'>
  <span id='first' class='active'></span>
  <span id='second'></span>
  <span id='third'></span>
  <span id='fourth'></span>
</div>

CSS

#indicator span.active { background-color: var(--darkblue); }

Javascript

const sections = document.querySelectorAll('section');
const indicator = document.getElementById('indicator');
const indicatorBoxes = [
  document.getElementById('first'),
  document.getElementById('second'),
  document.getElementById('third'),
  document.getElementById('fourth'),
];

window.addEventListener('scroll', () => {
  let currentSection = 0;
  sections.forEach((section, i) => {
    const rect = section.getBoundingClientRect();
    if (rect.top <= window.innerHeight / 2 && rect.bottom > window.innerHeight / 2) {
      cuurentSection = i;
    }
  });

  indicatorBoxes.forEach((box, i) => {
    box.classList.toggle('active', i === currentSection);
  });
});
BACK