Skip to content Skip to sidebar Skip to footer

How To Add Active Class To The List "href" That Equal Showed In The Viewport Section "data-nav"

I'm new to javascript language, and I'm stuck with my code and don't have any idea about how to solve my problem, and I'm sorry in advance if I can't explain the problem. You can f

Solution 1:

Here we go you can add/remove the class in the functions addActiveClass/removeActiveClass functions, like:

//Add class
navBar.querySelector('li a[href*="#'+section.getAttribute('id')+'"]').classList.add('your-active-class');

//Remove Class
navBar.querySelector('li a[href*="#'+section.getAttribute('id')+'"]').classList.remove('your-active-class');

NOTE: I've added some CSS to the menu just to make it clear for the test purpose.

WORKING SAMPLE:

// select all sections
const sections = document.querySelectorAll('section');

// select the navbar id
const navBar = document.getElementById('navbar__list');

// create a document fragment to hold all the lists
const frag = document.createDocumentFragment();

/**
 * End Global Variables
 * Start Helper Functions
 *
 */

/**
 * End Helper Functions
 * Begin Main Functions
 *
 */

// build the nav

for (let section of sections) {
  const sectionId = section.getAttribute('id');
  const sectionTitle = section.getAttribute('data-nav');
  const list = document.createElement('li');
  const links = document.createElement('a');

  // construct the li's
  links.setAttribute('href', `#${sectionId}`);
  links.innerText = sectionTitle;
  list.appendChild(links);
  links.classList = 'menu__link';
  frag.appendChild(list);

  // add event listener for smooth scroll
  links.addEventListener('click', function(event) {
    event.preventDefault();
    window.scrollTo({
      top: section.offsetTop - 60,
      behavior: 'smooth'
    });
  });
};
navBar.appendChild(frag);

// select the a tags inside navbar
const allLinks = navBar.querySelectorAll('a');


/* // Add class 'active' to section when near top of viewport */
// Get the Top of the section
function sectionView(section) {
  return section.getBoundingClientRect().top;
}


// Remove Active Class of all sections
function removeActiveClass(section) {
  navBar.querySelector('li a[href*="#'+section.getAttribute('id')+'"]').classList.remove('your-active-class');
  return section.classList.remove('your-active-class');
}

// Add Active Class to the required section
function addActiveClass(is_inview, section) {
  if (is_inview) {
    section.classList.add('your-active-class');
    navBar.querySelector('li a[href*="#'+section.getAttribute('id')+'"]').classList.add('your-active-class');
  };
}


// combine functions //
const activeSection = () => {
  sections.forEach(section => {
    const itemView = sectionView(section);
    viewport = () => itemView > -200 && itemView <= 400;
    removeActiveClass(section);
    addActiveClass(viewport(), section);
  });
};

// add eventlistener to window
window.addEventListener('scroll', activeSection);
li a.your-active-class{
    color: green;
}

.navbar__menu{
    position: fixed;
    background: white;
    float: right;
    width: 100%;
    left: 500px;
}
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">
<!-- 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</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>

  <!-- Add new sections  -->
  <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>
  <section id="section5" data-nav="Section 5">
    <div class="landing__container">
      <h2>Section 5</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>
</main>
<footer class="page__footer">
  <p>&copy Udacity</p>
</footer>

Post a Comment for "How To Add Active Class To The List "href" That Equal Showed In The Viewport Section "data-nav""