There is highlight for the nav bar list item problem

I tried to build a responsive navigation bar but there is a disfunction in highlighting navbar items while scrolling to a specific section. but only the fourth navbar item is highlighted correctly. I think there is a problem with the condition.

a view on what I mean

a view on what I mean

js code img 1

js code img 1

js code img 2

js code img 2

// defining my globale Variables
const myAllSections = document.querySelectorAll("section"),
  myNavList = document.querySelector("#navbar__list"),
  fragment = document.createDocumentFragment();

/* looping over all sections tags gathering section name by (data-nav) and merge it to 
created textnode then appending it to created link that appended to created list 
after that for performance enhancement we creating a fragment appending every list to it cuz
appending children to it does not cause page reflow and finally append the fragment to the ul*/
myAllSections.forEach(function (sec) {
  let myAddedLink = document.createElement("a"),
    myAddedLinkName = sec.getAttribute("data-nav"),
    textnode = document.createTextNode(myAddedLinkName),
    myAddedNavlist = document.createElement("li");

  myAddedLink.appendChild(textnode);
  myAddedNavlist.appendChild(myAddedLink);
  fragment.appendChild(myAddedNavlist);
  //adding an eventlistener so when clicking on section name in nav bar it will  direct me to clicked section block
  myAddedLink.addEventListener("click", function () {
    sec.scrollIntoView({ behavior: "smooth" });
  });
});

myNavList.appendChild(fragment);
/* the result creating a nav bar with all sections and
when ever a section added to dom it will added to nav bar list by its name */

/* looping overall sections removing active class and  when we scroll 
if the scroll position located into section view then we add active class to it then 
we can style active class later by css */
window.addEventListener("scroll", function () {
  myAllSections.forEach(function (scrolledsec) {
    scrolledsec.classList.remove("your-active-class");

    if (
      pageYOffset >= scrolledsec.offsetTop &&
      pageYOffset < scrolledsec.offsetTop + scrolledsec.offsetHeight
    ) {
      scrolledsec.classList.add("your-active-class");
    }
    //the result that when we scroll the section inview with the active class  will take a different style

    const myAllLinks = document.querySelectorAll("a"); // defining a variable contains all links to loop over it

    /*looping over all links when a link text equal section name (data-nav) and that section in active 
    the link will get highlighted in nav bar menu */
    myAllLinks.forEach((link) => {
      if (
        scrolledsec.getAttribute("data-nav") === link.innerText &&
        scrolledsec.classList.contains("your-active-class")
      ) {
        link.style.color = "red";
      } else {
        link.style.color = "white";
      }
      /* the result that when we scroll to specific section the 
      nav list with the same name as section name will get highlighted*/
    });
  });
});
// adding an event listener to the button to direct (scrolling) the clicker to the top of the page
const uptopbutton = document.querySelector("#scroll_button");

uptopbutton.addEventListener("click", function () {
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: "smooth",
  });
});
/*
 *
 * CSS written based on SMACSS architecture.
 * To learn more, visit: http://smacss.com/
 * 
 * For simplicity, no reset or normalize is added. 
 * To learn more, visit: https://css-tricks.com/reboot-resets-reasoning/
 *
*/


/* ---- Base Rules ---- */
body {
    background: rgb(136,203,171);
    background: linear-gradient(0deg, rgba(136,203,171,1) 0%, rgba(0,13,60,1) 100%);
    margin: 0;
    font-family: 'Merriweather', serif;
    color: #fff;
}


/* Typeography General*/
h1 {
    font-family: 'Fira Sans', sans-serif;
    font-size: 3em;
    margin: 2em 1rem;
}

@media only screen and (min-width: 35em){
    h1 {
        font-size: 7em;
        margin: 2em 4rem 1em;
    }
}

h2 {
    border-bottom: 1px solid #cc1;
    font-family: 'Oxygen', Sans-Serif;
    font-size: 3em;
    color: #fff;
}

p {
    line-height: 1.6em;
    color: #eee;
}

/* ---- Layout Rules ---- */
main {
    margin: 10vh 1em 10vh;
}

.main-hero {
    min-height: 40vh;
    padding-top: 3em;
}

section {
    position: relative;
    min-height: 80vh;
}


/* ---- Module Rules ---- */

/* Navigation Styles*/
.navbar__menu ul {
    padding-left: 0;
    margin: 100;
    text-align: left;
   
}

.navbar__menu li {
    display: inline-block;
    margin-left: 20px;
    cursor: pointer;
       
}

.navbar__menu ul li a:hover {
    color: aqua;
       
}

.navbar__menu .menu__link {
    display: block;
    padding: 1em;
    font-weight: bold;
    text-decoration: none;
    color: #000;
}

.navbar__menu .menu__link:hover {
    background: #333;
    color: rgb(189, 15, 15);
    transition: ease 0.3s all;
}

/* Header Styles */
.page__header {
    background: rgb(0, 0, 0);
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 5;
}
button {
    position: fixed;
    bottom: 0%;
    right: 0%;
    width:60px;
    height: 30px;
    border-radius: 50px;
    cursor: pointer;
    background: rgba(71, 12, 12, 0);
    color: rgb(255, 255, 255);
    
}
/* Footer Styles */
.page__footer {
    background: #000;
    padding: 3em;
    color: #fff;
}

.page__footer p{
    color: #fff;
}


/* ---- Theme Rules ---- */
/* Landing Container Styles */
.landing__container {
    padding: 1em;
    text-align: left;
}

@media only screen and (min-width: 35em){
    .landing__container {
        max-width: 50em;
        padding: 4em;
    }
}

section:nth-of-type(even) .landing__container {
    margin-right: 0;
    margin-left: auto;
    text-align: right; 
}

/* Background Circles */
/* Note that background circles are created with psuedo elements before and after */
/* Circles appear to be random do to use of :nth-of-type psuedo class */
section:nth-of-type(odd) .landing__container::before {
    content: '';
    background: rgba(255, 255, 255, 0.187);
    position: absolute;
    z-index: -5;
    width: 20vh;
    height: 20vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(even) .landing__container::before {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    top: 3em;
    right: 3em;
    z-index: -5;
    width: 10vh;
    height: 10vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(3n) .landing__container::after {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    right: 0;
    bottom: 0;
    z-index: -5;
    width: 10vh;
    height: 10vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}

section:nth-of-type(3n + 1) .landing__container::after {
    content: '';
    background: rgb(255,255,255);
    background: linear-gradient(0deg, rgba(255,255,255,.1) 0%, rgba(255,255,255,.2) 100%);
    position: absolute;
    right: 20vw;
    bottom: -5em;
    z-index: -5;
    width: 15vh;
    height: 15vh;
    border-radius: 50%;
    opacity: 0;
    transition: ease 0.5s all;
}


/* ---- Theme State Rules ---- */
/* Section Active Styles */
/* Note: your-active-class class is applied through javascript. You should update the class here and in the index.html to what you set in your javascript file.  */
section.your-active-class {
    background: rgb(134, 134, 134);
    background: linear-gradient(0deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0) 100%);
}

section.your-active-class .landing__container::before {
    opacity: 1;
    animation: rotate 4s linear 0s infinite forwards;
}

section.your-active-class .landing__container::after {
    opacity: 1;
    animation: rotate 5s linear 0s infinite forwards reverse;
}

/* Section Active Styles Keyframe Animations */
@keyframes rotate {
    from {
        transform: rotate(0deg)
                   translate(-1em)
                   rotate(0deg);
    }
    to {
        transform: rotate(360deg)
                   translate(-1em) 
                   rotate(-360deg);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Manipulating the DOM</title>
  <!-- Load Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">  <!-- Load Styles -->
  <link href="css/styles.css" rel="stylesheet">
  <style>
   .your-active-class{
    font-size: large;        
    }
  </style>
</head>
<body>
  <!-- HTML Follows BEM naming conventions 
  IDs are only used for sections to connect menu achors to sections -->
  <header class="page__header">
    <nav class="navbar__menu">
      <!-- Navigation starts as empty UL that will be populated with JS -->
      <ul id="navbar__list"></ul>
    </nav>
  </header>
  <main>
    <header class="main__hero">
      <h1>Landing Page </h1>
    </header>
    <!-- Each Section has an ID (used for the anchor) and 
    a data attribute that will populate the li node.
    Adding more sections will automatically populate nav.
    The first section is set to active class by default -->
    <section id="section1" data-nav="Section 1" class="your-active-class">
      <div class="landing__container">
        <h2>Section 1</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    <section id="section2" data-nav="Section 2">
      <div class="landing__container">
        <h2>Section 2</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    <section id="section3" data-nav="Section 3">
      <div class="landing__container">
        <h2>Section 3</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>

        <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
      </div>
    </section>
    <section id="section4" data-nav="Section 4">
    <div class="landing__container">
      <h2>Section 4</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>

      <p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
    </div>
  </section>
  <button id="scroll_button">Uptop</button>
    </main>
  <footer class="page__footer">
    <p>&copy Udacity</p>
  </footer>
<script src="js/app.js"></script>
</body>
</html>

thanks in advance

Answer

The problem is how you nest your call to myAllLinks.forEach within myAllSections.forEach. What’s happening is your marking the proper sections with "your-active-class" but then it gets unhighlighted when you iterate through all of the links in a section that isn’t being viewed.

You can fix this by extracting the myAllLinks.forEach to run after your myAllSections.forEach instead of within it.

window.addEventListener("scroll", function () {

  // Track the current scrolledsec

  let currentScrolledsec;

  // Add/remove the "your-active-class" to the proper sections first

  myAllSections.forEach(function (scrolledsec) {
    scrolledsec.classList.remove("your-active-class");

    if (
      pageYOffset >= scrolledsec.offsetTop &&
      pageYOffset < scrolledsec.offsetTop + scrolledsec.offsetHeight
    ) {
      scrolledsec.classList.add("your-active-class");

      // Set as current scrolledsec
      currentScrolledsec = scrolledsec;
    }
  });

  // Now highlight/unhighlight the links using the current scrolledsec in view.

  //the result that when we scroll the section inview with the active class  will take a different style

  const myAllLinks = document.querySelectorAll("a"); // defining a variable contains all links to loop over it
  /*looping over all links when a link text equal section name (data-nav) and that section in active 
  the link will get highlighted in nav bar menu */
  myAllLinks.forEach((link) => {
    if (currentScrolledsec.getAttribute("data-nav") === link.innerText) {
      link.style.color = "red";
    } else {
      link.style.color = "white";
    }
    /* the result that when we scroll to specific section the 
    nav list with the same name as section name will get highlighted*/
  });
});