The default fill
for an animation is "none"
, which makes an element revert back to its original styles after the animation completes. Calling commitStyles
at this point has essentially no effect.
Instead, you can use the "forwards"
fill to keep the styles after the animation. Then, call commitStyles()
after the animation finishes and immediately cancel
the animation to ensure that no more resources are consumed by it. Note that setting the fill
can achieve the effect of persisting styles by itself, but there are several drawbacks; for instance, it is difficult to change any styles on an element set by an animation (not using commitStyles
) and the browser has to maintain the animation indefinitely.
document.querySelector("button").addEventListener("click", evt => {
document.getElementById("target").animate([{
transform: 'translateX(400px)'
}], {
duration: 1000,
fill: "forwards"
}).finished.then(a => {
a.commitStyles();
a.cancel();
});
});
<div id="target">I can move</div>
<button>Move it</button>
As an aside, you can see that calling commitStyles
does work before the animation finishes (without setting fill
) since the animation styles are still active at that time.
document.querySelector("button").addEventListener("click", evt => {
const anim = document.getElementById("target").animate([{
transform: 'translateX(400px)'
}], 1000);
// Do NOT use this approach
setTimeout(() => anim.commitStyles(), 950);
});
<div id="target">I can move</div>
<button>Move it</button>