I want to make it so that elements with the class fade fade in when they are first visible on the screen then fade out when they leave the screen.
I want this animation to only happen once.
Below is what I have tried.
.fade {
/* transition: opacity 0.9s ease-in;*/
opacity: 0;
}
.fade.visible {
transition: opacity 0.9s ease-in;
opacity: 1;
}
window.addEventListener('scroll', fade)
function fade()
{
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');
}
}
}
Other than removing the event listener (which seems like doesn’t work for you for some reason) a simple change would be to add a global boolean flag which you toggle once after performing the animation. If the flag is true, just return early from the fade function
Something like this should work or at least be pretty close
This way
fadeshould only animate once so long asanimationHappenedisn’t set tofalseagain anywhere else in your code.