Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Problems with change the active list when scrolling navbar

I'm trying to change active when scrolling in nav bar but it's doesn't work with my code

Here, this is my js code

<script>
let navbar = document.getElementById("nav ul li");
    let viewportHeight = window.innerHeight;
    let navHeight = document.getElementById("nav ul li").offsetHeight;

    let navbarLinks = document.querySelectorAll("nav ul li a");

    window.addEventListener("scroll", e => {
        scrollpos = window.scrollY;
        navbarLinks.forEach(link => {
            let section = document.querySelector(link.hash);
            if (section.offsetTop <= scrollpos + 20 &&
                section.offsetTop + section.offsetHeight > scrollpos + 20) {
                link.classList.add("active");
            } else {
                link.classList.remove("active");
            }
        });
    });
</script>

Here, this is my html code

<nav>
        <div class="header">Profile</div>
        <ul class="nav-links">
            <li><a href="#page1" class="active">About</a></li>
            <li><a href="#page2">Social</a></li>
            <li><a href="#page3">MyWorks</a></li>
            <li><a href="#page4">Development</a></li>
            <li><a href="#page6">Encouragement</a></li>
            <li><a href="#page7">Technique</a></li>
        </ul>
    </nav>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Ok,

I think you should use document.querySelectorAll(...) instead of document.getElementById(...), (line 2 & 4)

because you are using a CSS QUERY SELECTOR. you should use getElementById only when you are selecting an element by it's id.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!