is anyone solved animation error in javascript

60 Views Asked by At

Error in my code is, I add condition to run a JavaScript function only one time but when I add if else logic web page can open all sections

here is my code logic:


let count = 0;
window.addEventListener('scroll', fade);
function fade()
{
  if (count < 1)
  {
    let animation=document.querySelectorAll('.fade');
    for (let i=0; i<animation.length; i++)
    {
      let windowheight=window.innerHeight;
      let top=animation[i].getBoundingClientRect().top;
      if (top < windowheight)
      {
      animation[i].classList.add('visible');
      }
      else
      {
      animation[i].classList.remove('visible');
      }    
    }
  }
  else
  {
    return ;
  }
  count++;
}

1

There are 1 best solutions below

3
someone On

Since you only need to handle the event once,

window.addEventListener('scroll', fade, {once: true});

You can safely remove count variable and if...else.