title: Use IntersectionObserver with rootMargin to change when reaching 50% viewport height
body: <p>I'm completely flummoxed by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin" rel="noreferrer"><code>rootMargin</code> property</a> of intersection observer.</p>
  
  <p>My goal is to add a class to an element when half it's height has crossed the vertical center of the viewport.</p>
  
  <p><a href="https://i.stack.imgur.com/uAil8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uAil8.png" alt="diagram of desired result"></a></p>
  
  <p>In my current project, nothing I do seems to impact the "root intersection rectangle" and the class is always added immediately. I've tested in latest Chrome and Firefox.</p>
  
  <p>Here's the reduced test case:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
  
  const options = {
    root: null, // default, use viewport
    rootMargin: '0px 0px -50% 0px',
    threshold: 0.5 // half of item height
  }
  
  const circle = document.getElementById('circle');
  
  const observerCallback = function(entries, observer) {
    console.log('intersected');
    circle.classList.add('intersected');
  }
  
  window.addEventListener('load', function(event) {
  
    const observer = new IntersectionObserver(observerCallback, options);
  
    observer.observe(circle);
  
  }, false);</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.circle {
    margin: 100vh auto;
    width: 200px;
    height: 200px;
    background-color: tomato;
    border-radius: 50%;
    transition: background-color 2s ease-in-out;
  }
  
  .circle.intersected {
    background-color: mediumseagreen;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="circle" id="circle"&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>