Incremental CSS animation based on scroll position

Viewed 343

I used the code below to play a paused CSS animation incrementally based on the window scroll position.

The problem I'm having now is that all the paused animations are triggered at the same time once I start scrolling. I'd like each animation to start only when its parent div comes into the viewport.

Any idea how I can do that? Thanks in advance.

window.addEventListener("scroll", () => {
  document.body.style.setProperty("--scroll", window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
}, false);
 

.quest_con {
  height: 100vh;
 }
.quest {
  animation: slide_down .5s linear infinite;
  animation-play-state: paused;
  animation-delay: calc(var(--scroll) * -1.5s);
  animation-iteration-count: 1;
  animation-fill-mode: both;
  opacity: 0;
}

@keyframes slide_down {
  0% {
    opacity: 0;
  }
  50% {
    transform: translate(0, -350px);
  }
  80% {
    opacity: 0;
  }
  100% {
    transform: translate(0, 0);
    opacity: 1;
  }
}
    <div class="col-12 quest_con quest_con_1">
       <i class="fas fa-question quest text_xxl color_2"></i>
       <i class="fas fa-running text_xl color_2"></i>
    </div>

    <div class="col-12 quest_con quest_con_2">
       <i class="fas fa-question quest text_xxl color_2"></i>
    </div>

    <div class="col-12 quest_con quest_con_2">
       <i class="fas fa-question quest text_xxl color_2"></i>
    </div>

1 Answers

you can archive this with the IntersectionObserver API easily. You can just have a look at the MDN Documentation: MDN - IntersectionObserver API IntersectionObserver manages all the "In View" states for your Elements.

Related