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?
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.