Animate each section as I scroll down/up

What’s the best way to animate the sections of my page so that, as I scroll down, any new section appearing is animated with a fade-in, and the previous one disappears with a fade-out animation, and equivalently for when I scroll up?

I was using a plugin OnScreenDetector (adding 1 element right before each section), setting up all sections as not visible, and when each screen detector is visible, animate and show the next section. But seems like adding a lot of workflow complexity, and when I want to animate “Do every time”, it’s maybe not the best way.

Any ideas?

OK I managed to do it by asking ChatGPT.

Basically you add an HTML header on the page with this CSS:

<style>
  /* Ensure sections start hidden */
  #section-screens, #section-partners, #section-discover, 
  #section-instant, #section-features, #section-counter, #section-blog {
    opacity: 0;
    transform: translateY(40px);
    transition: opacity 0.6s ease-out, transform 0.6s ease-out;
  }
</style>

And then you add a “Run javascript” on page load with this code:

function applyScrollEffects() {
  const sections = document.querySelectorAll(
    "#section-screens, #section-partners, #section-discover, #section-instant, #section-features, #section-counter, #section-blog"
  );

  if (sections.length === 0) {
    setTimeout(applyScrollEffects, 500);
    return;
  }

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.style.opacity = "1";
          entry.target.style.transform = "translateY(0px)";
        } else {
          entry.target.style.opacity = "0";
          entry.target.style.transform = "translateY(40px)";
        }
      });
    },
    { threshold: 0.5 }
  );

  sections.forEach((section) => observer.observe(section));
}

setTimeout(applyScrollEffects, 1500);

Just keep in mind that all those #section-screens, etc. are the ID attribute of each section I want to animate. It adds a nice fade-in/out and moving animation effect to each section tagged, when such a section is visible on screen.

Hope it helps!

This topic was automatically closed after 70 days. New replies are no longer allowed.