title: How to use Intersection Observer instead of window.onscroll?
body: <p>I have the current JS for a modification to the navbar and a scroll-to-top button:</p>
  <pre><code>const navbar = document.querySelector('nav');
  const scrolltotop = document.querySelector('.scrolltotop');
  window.onscroll = () =&gt; {
      if (window.scrollY &gt; 300 &amp;&amp; window.scrollY &lt; 600) {
          navbar.classList.add('nav-active');
      } else if (window.scrollY &gt; 600) {
          scrolltotop.classList.add('scrolltotop-active');
          navbar.classList.add('nav-active');
      } else {
          scrolltotop.classList.remove('scrolltotop-active');
          navbar.classList.remove('nav-active');
      }
  };
  </code></pre>
  <p>Now I have found out about performance issue with window.onscroll method and that you should the &quot;Intersection Observer&quot; instead but I cannot figure out how to do it.
  This is my current status:</p>
  <pre><code>const navbars = document.querySelector('nav');
  const scrolltotops = document.querySelector('.scrolltotop');
  const config = {
    rootMargin: '0px'
  };
  let observer = new IntersectionObserver(function (entries, self) {
    entries.forEach(entry =&gt; {
      if (entry.isIntersecting) {
        intersectionHandler(entry); 
      }
    });
  }, config);
  
  navbars.forEach(navbar =&gt; {
    observer.observe(navbar);
  });
  function intersectionHandler(entry) {
    const id = entry.target.id;
    const currentlyActive = document.querySelector('nav.nav-active');
    const shouldBeActive = document.querySelector('nav');
  
    if (currentlyActive) {
      currentlyActive.classList.remove('nav-active');
    }
    if (shouldBeActive) {
      shouldBeActive.classList.add('nav-active');
    }
  }
  </code></pre>
  <p>The navbar is this</p>
  <pre><code>&lt;nav class=&quot;bg-transparent shadow-lg sticky top-0 z-50 h-[3.75rem] transition duration-500 ease-in-out&quot;&gt;
   ...
  &lt;/nav&gt;
  </code></pre>
  <p>This is the applied CSS</p>
  <pre><code>.nav-active {
    @apply bg-blue-800 !important;
    box-shadow: 5px -1px 12px -5px grey;
  }
  .scrolltotop-active {
    display: flex !important;
  }
  </code></pre>
  <p>But it doesn't work and I don't have enough knowledge how to do it right. Goal is to change navbar from transparent to blue background color on scroll down 300px and show a scroll-to-top button at 600px scrolling.
  What is missing here?</p>