'Highlight navigation item when it is on viewport

I am trying to highlight the navigation item by changing the color when the section is on the viewport.(There is more text in each sections) It does not work and I can not figure out why and how to solve it. I wanted to use 'IntersectionObserver' but it seems I have not done it correctly?? could someone help me?

const sections = Array.from(document.querySelectorAll('section'));
const navBar = document.querySelector('#navbar__list');

const createNavItem = () => {
  for (section of sections) {
    href = section.getAttribute('id');
    navName = section.getAttribute('data-nav');
    navItem = document.createElement('li');

    const setNavBar = () => {
      navItem.innerHTML = `<a href="#${href}" class="nav_item"">${navName}</a>`;
      navBar.appendChild(navItem);
    };
    setNavBar();
  }
};

createNavItem();

const activeSection = (elem) => {
  if (document.querySelector('.menu__link__active') !== null) {
    navBar.classList.remove('menu__link__active');
  }
  const currentSection = document.querySelector(
    `a[href='#${section.getAttribute('id')}']`
  );
  currentSection.classList.add('menu__link__active');
};

const intersect = (entries) => {
  for (entry of entries) {
    if (entry.isIntersecting) {
      activeSection(entry.target);
    }
  }
};

const observer = new IntersectionObserver(intersect, {
  root: null,
  rootMargin: '-50% 0px',
  threshold: 0,
});

for (section of sections) {
  observer.observe(section);
}
.menu__link__active {
  /* background: #333; */
  background: rgb(217, 36, 237);
  transition: ease 0.3s all;
}
<!DOCTYPE >
<html lang="en">
 <head>
    <meta charset="UTF-8" />
     <link href="css/styles.css" rel="stylesheet" />
  </head>
  
  <body>
<header class="page__header">
      <nav class="navbar__menu">
        <ul id="navbar__list"></ul>
      </nav>
    </header>
     <main>
      <header class="main__hero">
        <h1>Landing Page</h1>
      </header>
      <section id="section1" data-nav="Section 1" class="your-active-class">
       
          <h2>Section 1</h2> 
      </section>
      <section id="section2" data-nav="Section 2" class="your-active-class">
        
          <h2>Section 2</h2> 
      </section>
      <section id="section3" data-nav="Section 3" class="your-active-class">
       
          <h2>Section 3</h2> 
      </section>
       </section>
    </main>
    <script type="text/javascript" src="./js/app.js"></script>
  </body>
</html>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source