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

118
Views
JavaScript: How to better indicate (highlight) current nav page during scroll than just using "scrollY > x"

I currently have a simple webpage layout that is divided in 4 sections (HOME / ABOUT / SKILLS / CONTACT).

Here is my JS code that highlights a specific section from the Nav-bar when a certain pixel amount has been reached during scroll:

let home = document.querySelector(".btn1")
let about = document.querySelector(".btn2")
let skills = document.querySelector(".btn3")
let contact = document.querySelector(".btn4")

function highlight(){
  if(window.scrollY > 1)
  {
    home.classList.add("highlight")
  }

  if(window.scrollY > 550)
  {
    home.classList.remove("highlight")
    about.classList.add("highlight")
  }
  else{
    about.classList.remove("highlight")
  }

  if(window.scrollY > 1210)
  {
    skills.classList.add("highlight")
    about.classList.remove("highlight")
  }
  else{
    skills.classList.remove("highlight")
  }

  if(window.scrollY > 2050)
  {
    contact.classList.add("highlight")
    skills.classList.remove("highlight")
  }
  else{
    contact.classList.remove("highlight")
  }
}

window.addEventListener("scroll", highlight);

This works fine on my 24" monitor, but gets inaccurate if viewport height gets bigger, such as on a 27" monitor.

What better way can I target each page section with scroll?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Make a script where you define the elements that you need to reach in order for the state to update (with the use of .offsetTop)

Now the pixels value will dynamically change as the viewport changes.

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!