Skip to content
Advertisement

How to play animation only when the element is on screen

I’m working in React, and I need to know when an element is on screen to play a fade animation, and make it appear on screen. Because the animation always plays when the page is loaded, but if you have to scroll to see the element, then you’ll never see the animation 🙁

<Grid container className="AnimationContainer">
  <img src="/images/animation1/circle.svg" className="Animation1-1" />
  <img src="/images/animation1/calculator.svg" className="Animation1-2" />
</Grid>

In my CSS file I have:

.AnimationContainer {
  place-content: center;
  height: 200px;
  width: 100%;
}
.Animation1-1 {
  animation: fading 2s;
}
.Animation1-2 {
  animation: fading 1.2s;
}
@keyframes fading{
  0%{opacity:0}
  100%{opacity:1}
}

What can I do here to only play it when the Grid “AnimationContainer” or when the img “Animation1-1″/”Animation1-2” are visible?

Advertisement

Answer

Use Intersection Observer to detect when the element is visible and only set the animation property once it is. This is pretty easy to do using react-intersection-observer:

import { useInView } from "react-intersection-observer"

const Example => () => {
  const [ref, inView] = useInView({ threshold: 0.5 })

  return (
    <Grid ref={ref} container className="AnimationContainer">
      <img src="/images/animation1/circle.svg" className={inView ? "Animation1-1" : null} />
      <img src="/images/animation1/calculator.svg" className={inView ? "Animation1-2" : null} />
    </Grid>
  )
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement