Below is my code that highlights a category in the nav-bar once a specific div's offsetTop is reached by scrolling through the webpage.
let page1 = document.querySelector(".A").offsetTop
let page2 = document.querySelector(".B").offsetTop
let page3 = document.querySelector(".C").offsetTop
let page4 = document.querySelector(".D").offsetTop
let home = document.querySelector(".home")
let about = document.querySelector(".about")
let contact = document.querySelector(".contact")
let random = document.querySelector(".random")
window.addEventListener("scroll", function(){
/* ---------------------------------------- PAGE 1 */
if(window.scrollY > 1)
{
home.classList.add("highlight");
}
/* ---------------------------------------- PAGE 2 */
if(window.scrollY > page2 - 100){
about.classList.add("highlight")
home.classList.remove("highlight");
}
else{
about.classList.remove("highlight")
}
/* ---------------------------------------- PAGE 3 */
if(window.scrollY > page3 - 100){
contact.classList.add("highlight")
about.classList.remove("highlight")
}
else{
contact.classList.remove("highlight")
}
/* ---------------------------------------- PAGE 4 */
if(window.scrollY > page4 - 100){
random.classList.add("highlight")
contact.classList.remove("highlight")
}
else{
random.classList.remove("highlight")
}
});
Screenshot [1]: https://i.stack.imgur.com/VamWP.png
My issue is the offsetTop values do not reset to their new values when window is being resized, unless I refresh browser! Only then does it become accurate again during scroll.
I heard that window.onresize could help but I cant seem to find the right way to add it with my code.
Thank you in advance!