Friday, 12 August 2022

Why can't I modify the property js animate() applies to an element?

After the animation finishes, the click event will no longer work, in fact, changing the value from the dev tools will not work either. Using fill: 'none' will work, but I want to use the styling applied by the animation.

Is this expected behaviour ? The animation finishes and applies the style to the element as an inline style (or does it?), why can't it be modified in this case ? Is there a way to keep the style that the animation applies and then modify it?

Example: event listener no longer works after animation finished

let square = document.querySelector('.circle')

square.addEventListener('click', () => {
    square.style.transform = 'translateY(50px)'
})

let animation = [
    {transform: 'translateY(100px)'}
]

square.animate(animation, {duration: 2000, fill: 'both'})
.circle {
  width: 100px;
  height: 100px;
  background-color: #c965a6;
  border-radius: 50%;
}
<div class='circle'></div>

Edit: Found a solution

Use fill: 'none', listen for when the animation finishes and manually apply the final styling to the element.

let anim = square.animate(animation, {duration: 2000, fill: 'none'})
anim.addEventListener('finish', () => {
  square.style.transform = 'translateX(0px)'
})

Though this seems more like an workaround, I'd still like to know why you can't modify properties applied by an animation



from Why can't I modify the property js animate() applies to an element?

No comments:

Post a Comment