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

98
Views
ScrollSpy not working with dynamic height

I'm working on a single-page website, and am trying to implement a scroll-spy feature:

Here's what my navbar looks like:

<nav class="menu">
        <ul class="nav-links">
            <li><a href="#home">Home</a></li>
            <li><a href="#about">About Us</a></li>
            <li><a href="#aboutStem">What is STEM</a></li>
            <li><a href="#quotes">Products</a></li>
            <li><a href="#accomplishments">Contact Us</a></li>
        </ul>
    </nav>

In addition to this, I have created sections for each link in the navbar. The scrollspy is as follows:

document.addEventListener('DOMContentLoaded', () => {

const scrollSpy = () => {
    const targets = document.querySelectorAll('section');
    console.log(targets)
    const options = {
      threshold: 0.5,
    };

    if ('IntersectionObserver' in window) {
      const inView = target => {
        const interSecObs = new IntersectionObserver(entries => {
          entries.forEach(entry => {
            const elem = entry.target;
            const currentNav = document.querySelector(`[href='#${elem.id}']`);
            currentNav?.classList.toggle('active', entry.isIntersecting);
          })
        }, options);
        interSecObs.observe(target)
      };
      targets.forEach(inView);

    }
  };

  scrollSpy();

})

The scrollspy works fine as long as I specify the absolute height of a section, however, for responsiveness, I am using height: fit-content and that is causing errors.

Any help would be appreciated.

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!