Intersection Observer & Efficient Scroll Handling

How can you implement efficient scroll-based navigation highlighting?
const navObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    const id = entry.target.id;
    const navItem = document.querySelector(`nav a[href="#${id}"]`);
    
    if (entry.intersectionRatio > 0) {
      navItem?.classList.add('active');
    } else {
      navItem?.classList.remove('active');
    }
  });
}, {
  rootMargin: '-50% 0px',
  threshold: 0
});
Next Question (13/20)