2

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Omar Tan
  • 187
  • 1
  • 12

1 Answers1

2
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}

This decrements the index with each iteration. The loop stops when window.scrollY + 50 < sections[index].offsetTop is false, and the index remains to the value of the last 'passed' check.

It is later used to update links[index].classList.add('active');

It could have been written like this also:

while (index >= 0 && window.scrollY + 50 < sections[index].offsetTop) {
    index--
}

It is required to check if index has a adequate value (aka not -1 or lower), or it will error when it reached -1, as sections[-1].something does not exist.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Andu Andrici
  • 853
  • 1
  • 5
  • 12