In this example we have two buttons, labeled "Commit styles" and "Fill forwards". Both buttons animate when you click them, and both buttons persist the final state of the animation.
The difference, though, is that "Fill forwards" only uses fill: "forwards"
to persist the animation's final state: this means that the browser has to maintain the animation's state indefinitely, or until it can be automatically removed.
However, the "Commit styles" button waits for the animation to finish, then calls commitStyles()
, then cancels the animation, so the finished style is captured as the value of the style
attribute, rather than as the animation state.
<button class="commit-styles">Commit styles</button>
<br />
<button class="fill-forwards">Fill forwards</button>
button {
margin: 0.5rem;
}
JavaScript
const commitStyles = document.querySelector(".commit-styles");
let offset1 = 0;
commitStyles.addEventListener("click", async (event) => {
// Start the animation
offset1 = 100 - offset1;
const animation = commitStyles.animate(
{ transform: `translate(${offset1}px)` },
{ duration: 500, fill: "forwards" },
);
// Wait for the animation to finish
await animation.finished;
// Commit animation state to style attribute
animation.commitStyles();
// Cancel the animation
animation.cancel();
});
const fillForwards = document.querySelector(".fill-forwards");
let offset2 = 0;
fillForwards.addEventListener("click", async (event) => {
// Start the animation
offset2 = 100 - offset2;
const animation = fillForwards.animate(
{ transform: `translate(${offset2}px)` },
{ duration: 500, fill: "forwards" },
);
});
Result
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4