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.