This question is in reference to this post.
In summary, the requirement is to have the links in the navigation to change status based on the current scroll position, I was able to get the code presented here to work, but one line which I don't understand why it's done this way is
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
I would've commented on the original answer post, but apparently, my reputation is not enough yet.
This is the whole JavaScript code
const links = document.querySelectorAll('.links');
const sections = document.querySelectorAll('section');
function changeLinkState() {
let index = sections.length;
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
links.forEach((link) => link.classList.remove('active'));
links[index].classList.add('active');
}
changeLinkState();
window.addEventListener('scroll', changeLinkState);
Why is the while loop needed and since it's empty wouldn't it do anything? I tried removing the while loop and it ended up breaking the code.