tt9
tt9

Reputation: 6069

override the styles set by web animation api

I am using web animations api to animate a div to a specific height. I am using fill mode 'forwards' to preserve the height post animation. However, later on I would like to manually set the height through CSS back to 'auto', but by setting the fill mode to forwards it seems to prevent CSS's ability to affect the height property after the animation finishes, even if I set it on the element.

I cannot set the height back to auto immediately after the animation plays, so I was wondering if there was a way to override the properties set by fill 'forwards'?

Upvotes: 3

Views: 1268

Answers (2)

brianskold
brianskold

Reputation: 972

Styles set by CSS Animations and the Web Animations API affect the animations level of the CSS cascade. There is a description of this in the combining effects section of the spec. As a result, if you set style in a stylesheet or style attribute, unless that style is !important, the animation style will override it.

In your case, you have a couple of options:

  1. When you want to replace the 'fill' style with something else, call cancel() on the animation at the same time you update the style.
  2. Use FLIP animation. i.e. Set the destination style to the specific height you want. Make your animation finish at that same height and don't use a forwards fill mode. In the coming months Firefox/Chrome/polyfill should release an update to make this part easier by not requiring you to specify the endpoint of the animation.

Upvotes: 2

tt9
tt9

Reputation: 6069

So I read an article, online, I can't remember where I found it. But it states that CSS cannot override the fill mode styles.

I ended up creating a function that just animates the properties to each other with 0 duration.

it looks like this:

  setWebAnimationApiStyles(nativeElement, styleTargets) {
    return new Promise((res, rej) => {
      const animation = nativeElement.animate([styleTargets, styleTargets], { duration: 0, delay: 0, fill: 'forwards' });
      animation.onfinish = (evt) => {
        res(animation);
      };
      animation.play();
    });
  }

The style targets object is just an object formatted how you would have your web animations object:

{    
    height: 'auto'
}

And it seems to work for now.

Upvotes: 1

Related Questions