The Element
interface's animate()
method is a shortcut method which creates a new Animation
, applies it to the element, then plays the animation. It returns the created Animation
object instance.
Note: Elements can have multiple animations applied to them. You can get a list of the animations that affect an element by calling Element.getAnimations()
.
animate(keyframes, options)
In this example we use the animate()
method to rotate and scale an element.
HTML
<div class="newspaper">Spinning newspaper<br />causes dizziness</div>
CSS
html,
body {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
background-color: black;
}
.newspaper {
padding: 0.5rem;
text-transform: uppercase;
text-align: center;
background-color: white;
cursor: pointer;
}
JavaScript
const newspaperSpinning = [
{ transform: "rotate(0) scale(1)" },
{ transform: "rotate(360deg) scale(0)" },
];
const newspaperTiming = {
duration: 2000,
iterations: 1,
};
const newspaper = document.querySelector(".newspaper");
newspaper.addEventListener("click", () => {
newspaper.animate(newspaperSpinning, newspaperTiming);
});
Result
In the demo Down the Rabbit Hole (with the Web Animation API), we use the convenient animate()
method to immediately create and play an animation on the #tunnel
element to make it flow upwards, infinitely. Notice the array of objects passed as keyframes and also the timing options block.
document.getElementById("tunnel").animate(
[
{ transform: "translateY(0px)" },
{ transform: "translateY(-300px)" },
],
{
duration: 1000,
iterations: Infinity,
}
);
In newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to. For example, consider this simple animation — the Keyframe object looks like so:
let rotate360 = [{ transform: "rotate(360deg)" }];
We have only specified the end state of the animation, and the beginning state is implied.