0

I have some sections and some navigation links in my page. Im using Intersection Observer to add an active class to a respective link that redirect to this section. In some part of my page, 2 sections are visibles i want to add the active class to the most visible section (only once at time) but i don't know how:

enter image description here

Here is the Intersection Observer code:

    const sectObserver = new IntersectionObserver(entries => {
    for (entry of entries) {
      // here i get the section id and the link classList:
      const { id } = entry.target,
      { classList } = document.querySelector(`#to-${id}`);
      if (entry.intersectionRatio) {
        classList.add('active');
      } else {
        classList.remove('active');
      };
    };
  });

And here the instance of the targets observer:

    document.querySelectorAll('section:not(#get-cv, #skills)')
      .forEach(link => sectObserver.observe(link));
sbgib
  • 5,580
  • 3
  • 19
  • 26
gianlop3z
  • 107
  • 2
  • 9

1 Answers1

1

The Intersection Observer has a threshold option which defines how much of a section (from 0 to 1) needs to be visible before it runs your function. Try to get this percentage right for the sections on your page.

const options = { threshold: 0.5 };
const sectObserver = new IntersectionObserver(entries => {
  for (entry of entries) {
    // here i get the section id and the link classList:
    const { id } = entry.target,
    { classList } = document.querySelector(`#to-${id}`);
    if (entry.intersectionRatio) {
      classList.add('active');
    } else {
      classList.remove('active');
    };
  };
}, options);
sbgib
  • 5,580
  • 3
  • 19
  • 26