title: add class to element in viewport
body: <p>I have five sections on my page, and I am trying to add class &quot;active&quot; to the section in the view port.
  I tried this code but it is not working properly.
  the code saves all elements with tag name &quot;section&quot; in a node list then created an array of this list, I looped over the array and added an event listener for each element, then I tested if the element is in the viewport is so I add the class else I remove the class.
  the problem is once the page is scrolled all the five sections will have the class &quot;active&quot; which means that multiple elements have the class &quot;active&quot; at the same time even though only one section is viewed in the port and when I keep on scrolling down the sections that are moved upward out of the viewport have their class &quot;active&quot; removed.
  how can i have one element with the class &quot;active&quot;<a href="https://i.stack.imgur.com/6HOlp.jpg" rel="nofollow noreferrer">image of code</a> at a time?</p>
  <pre><code>//values of viewport
  const viewWidth = document.documentElement.clientWidth;
  const viewHeight = document.documentElement.clientHeight;
  
  //set class active to section in viewport
  function sectionInView(x) {
      for (let i = 0; i in x; i++) {
          document.addEventListener(&quot;scroll&quot;, function () {
              let el = x[i].getBoundingClientRect();
              if (el.top &gt;= 0 &amp;&amp; el.left &gt;= 0 &amp;&amp; el.bottom &lt;= viewHeight &amp;&amp; el.right &lt;= viewWidth) {
                  x[i].setAttribute(&quot;class&quot;, &quot;active your-active-class&quot;);
  
              }
              else {
  
                  x[i].removeAttribute(&quot;class&quot;, &quot;active your-active-class&quot;);
              }
          });
      }
  }
  sectionInView(sectionListArray);
  </code></pre>