I have a CSS animation that uses keyframes
which is executed only once when the page loads (see example cited) .
The result I am looking for is a JavaScript or JQuery control that prevents the execution of the animation until it is in the area of the page that the user is viewing (the viewport ) .
I have connected the animation to a class that I apply to the element with JavaScript but I have no idea how to capture the event that should trigger the action.
How is the presence of an element in the viewport detected?
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
.animate {
animation-name: example;
animation-duration: 4s;
}
#cube {
width: 100px;
height: 100px;
background-color: red;
}
<!-- La clase animate viene añadida posteriormente con JavaScript -->
<div id="cube" class="animate"></div>
A good option is to use the Intersection Observer API to detect when the element appears in the viewport