Search code examples
javascriptscrollhyperlinkpositionviewport

Javascript scroll event adding class


Hello guys i have a problem with scroll event:

I want to add a class to some link when the section is in the viewport ( is visible ), but the problem is if my scroll position is between the selected range( in if statement ) everything is ok the class is added to the link. But if i continuously scroll to the next section the class is infinite added. How can i only add it once the if statement is true (scroll position is between the selected range) ?

// Element position
  const attractionSectionPos = Math.floor(ui.attractions_section.getBoundingClientRect().top);

// For intro section
  if(attractionSectionPos <= 250 && attractionSectionPos >= -450) {

    // Remove the active link if we have more than one
    document.querySelectorAll('.active').forEach(link => link.classList.remove('active'));
                
    // Add the class when section is in viewport
    document.querySelector('[data-link="attractions"]').classList.add('active');

    // Prevent default so we only add the class once
    e.preventDefault();

  // Remove the class if section is not in viewport
  } else { document.querySelector('[data-link="attractions"]').classList.remove('active') }

If i add e.preventDefault() it gives me a bunch of errors.

E.g: Uncaught TypeError: e.preventDefault is not a function

This is how my console looks


Solution

  • I added in the if statement the following:

    !document.querySelector('[data-link="attractions"]').classList.contains('active')

    Now everything works smoothly and adds the class only once when the section is in the viewport