Scrollspy

Written by Walter White

Scrollspy

Bootstrap 5 Scrollspy

class ScrollSpy {
  constructor() {
    this.sections = [...document.querySelectorAll('section[id]')];
    this.menuLinks = document.querySelectorAll('.nav-item a');
    this.navoffset = document.querySelector('.navbar').clientHeight || 0;
    this.navToggle = document.querySelector('.navbar-toggler');
    this.mobileMenu = document.querySelector('.navbar-collapse');
    this.scrollHandle = this.scrollHandle.bind(this);
    document.addEventListener('scroll', this.scrollHandle, false);
    document.addEventListener('resize', this.scrollHandle, false);
    document.addEventListener('readystatechange', this.scrollHandle, false);
    this.scrollHandle();
  }

  scrollHandle() {
    const scrollPosition =
      document.documentElement.scrollTop || document.body.scrollTop;
    this.menuLinks.forEach((link) => link.classList.remove('active'));
    this.sections.forEach((section) => {
      const offset = section.offsetTop - this.navoffset;
      if (offset <= scrollPosition) {
        this.menuLinks.forEach((link) => link.classList.remove('active'));
        const target = document.querySelector(`a[href="#${section.id}"]`);
        if (!target.hash) return;
        target.classList.add('active');
        if (target.parentElement.classList.contains('dropdown-menu')) {
          target.parentElement.parentElement.firstChild.classList.add('active');
        }
        if (this.mobileMenu.classList.contains('show')) {
          this.navToggle.click();
        }
      }
    });
  }
}

// Instantiate the ScrollSpy class
new ScrollSpy();
Go back