Making navigation links highlight when relevant element passes underneath it, using JavaScript/JQuery?

后端 未结 2 920
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 03:42

I have a single page website with the navigation menu position:fixed at the top of the page.

When I click a link from the navigation menu the page scrolls

2条回答
  •  孤独总比滥情好
    2021-02-09 04:09

    This should solve it. User Manually Scrolls on getting to a section, the Nav Link is Highlighted

    let mainNavLinks = document.querySelectorAll(".glossaryContainer ul li a");
    let
      mainSections = document.querySelectorAll("main section");
    window.addEventListener("scroll", event => {
      let fromTop = window.scrollY;
      mainNavLinks.forEach(link => {
        let section = document.querySelector(link.hash);
        if (section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight >
          fromTop) {
          link.classList.add("current");
        } else {
          link.classList.remove("current");
        }
      });
    });
    
    
    

    Section 1

    Lorem, ipsum dolor sit amet consectetur adipisicing elit. Officiis, blanditiis expedita? Earum eligendi pariatur quaerat quos expedita ab quibusdam ratione veniam in, mollitia fuga repudiandae?

    Section 2

    Ratione nulla nam, ipsa dignissimos corrupti veniam nostrum, laudantium asperiores sequi numquam placeat velit voluptate in praesentium non labore unde incidunt laborum maxime quae magni.

    Section 3

    Soluta quibusdam ad nostrum vel voluptate delectus sequi dolores quia quaerat officia corrupti, aperiam fugit facere debitis repudiandae praesentium sapiente inventore repellendus, nemo commodi alias!

提交回复
热议问题