title: Confused about highlighting active menu item on scroll (Vanilla JS)
body: <p>I found this function which highlights the active menu anchors when you scroll to sections that have the same id. I understand how most of the code works, but I don't get how the window onscroll event knows how to update the right anchor tag with the .active class. </p>
  
  <p>All the JS:
  <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>  var section = document.querySelectorAll(".section");
    var sections = {};
    var i = 0;
  
    Array.prototype.forEach.call(section, function(e) {
      sections[e.id] = e.offsetTop;
    });
  
    window.onscroll = function() {
      var scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
  
      for (i in sections) {
        if (sections[i] &lt;= scrollPosition) {
          document.querySelector('.active').setAttribute('class', ' ');
          document.querySelector('a[href*=' + i + ']').setAttribute('class', 'active');
        }
      }
    };</code></pre>
  </div>
  </div>
  </p>
  
  <p>From this Pen: <a href="https://codepen.io/zchee/pen/ogzvZZ" rel="nofollow noreferrer">https://codepen.io/zchee/pen/ogzvZZ</a></p>
  
  <p>This part confuses me: </p>
  
  <pre><code>document.querySelector('a[href*=' + i + ']').setAttribute('class', 'active');
  </code></pre>
  
  <p>I get that <code>setAttribute</code> adds a class of active to the anchor tag — but how does <code>querySelector</code> find the right anchor to update when you scroll? </p>
  
  <p>I tried logging the index variable <code>[i]</code> from the (for in array loop) to get the id of the current section (onscroll) but it returns the current scroll position (as a number). </p>
  
  <p>This is why I don't get why the inserted 'i' variable here: <code>('a[href*=' + i + ']')</code> represents the corresponding section id in the onscroll event. </p>
  
  <p>I guess it doesn't help that I don't really understand how this forEach function operates:</p>
  
  <pre><code>Array.prototype.forEach.call(section, function(e) {
  sections[e.id] = e.offsetTop;
  });
  </code></pre>
  
  <p>I get that it loops through all sections and pushes the <code>sections[e.id]</code> to the empty object <code>sections = {}</code> which is used later in the onscroll event — but that's where my understanding stops. :-/</p>
  
  <p>I'm sorry I don't know how to phrase this question better. I've spent hours trying to wrap my head around it. I can't find any topic examples that are similar to this, but I want to understand how it works before I use it anywhere. </p>
  
  <p>Would greatly appreciate some feedback! :-)</p>