Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger this animation to start once in viewport?

How can I trigger this animation to start once in viewport?

<div class="monster"></div>

.monster {
  width: 200px;
  height: 200px;
  margin: -50px auto;
  background: url('/wp-content/uploads/2021/07/sprite1.png') left center;
  animation: play 2.8s steps(15);
  animation-iteration-count: 1
}

@keyframes play {
    100% { background-position: -3000px; }
}
like image 936
Matt Partridge Avatar asked Oct 25 '25 09:10

Matt Partridge


1 Answers

Use an IntersectionObserver in javascript to detect when the element is on screen, then trigger the class that plays the animation like this (I changed your animation values since you wouldn't see them in a SO snippet):

const element = document.querySelector('.monster');
const observer = new IntersectionObserver(entries => {
  element.classList.toggle( 'animation', entries[0].isIntersecting );
});

observer.observe( element );
.monster {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  background: black;
}
main {
  margin: 1000px auto;
}

@keyframes play {
    100% { background: red; }
}

.animation {
  animation: play 2.8s steps(15);
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

.monster:after {
  position: fixed;
  content: 'Keep scrolling!';
  left: 50%;
  top: 50%;
  opacity: 0;
  transform: translate(-50%,-50%);
  transition: opacity .4s;
}
.monster:not(.animation):after {
  opacity: 1;
}
<main>
  <div class="monster"></div>
</main>
like image 59
somethinghere Avatar answered Oct 27 '25 22:10

somethinghere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!