Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding animation-fill-mode: forwards in JavaScript/CSS

I have some text I am animating in, and I do so using CSS keyframes. I keep the look of the end result of the animation, so I'm using animation-fill-mode: forwards to do so, like this:

#my-text {
    opacity: 0;
}

.show-me {
    animation-name: show-me;
    animation-duration: 2s;
    animation-fill-mode: forwards
}

@keyframes show-me {
    100% {
        opacity: 1;
    }
}

I then add the show-me class to the element using jQuery:

$('#my-text').addClass('show-me');

Later, after the animation is complete, I try to change the opacity of the element through code, but an unable to do so:

// this won't change the opacity, unfortunately
$('#my-text').css('opacity', 0);

Here's an example that shows the issue: http://jsfiddle.net/x3mbkbwL/2/

How do I override the value set from the animation when using fill-mode forwards? I know I can remove the class (in this case "show-me") when I need to change the element's opacity, but it seems like I should be able to directly override the css in JavaScript and it would override the opacity.

like image 589
Skitterm Avatar asked Oct 19 '22 20:10

Skitterm


1 Answers

Seems like CSS attributes set by animation-fill-mode: forwards can't be overwritten on the same element.

Either: Add a parent wrapper around

One solution is to put a wrapper around the element that has animation-fill-mode: forwards set. Then, in order to overwrite forwarded attributes, you would only update the parent instead.

<div id="parent">
    <div id="my-text">I just faded in!</div>
</div>

Then "overwrite" opacity only on the parent:

$('#parent').css('opacity', 0);

I've implemented the changes to your fiddle here: http://jsfiddle.net/x3mbkbwL/3/

Or: Nest a wrapper inside

If you prefer, you could alternatively add another child element instead:

<div id="my-text">
    <span id="wrapper">I just faded in!</span>
</div>

Then "overwrite" opacity only on the nested wrapper:

$('#wrapper').css('opacity', 0);

Both approaches work best if the forwarded opacity is set to 1. If it's forwarded to 0 then it obviously won't work as the element is then already hidden.

like image 147
Lars Blumberg Avatar answered Oct 21 '22 16:10

Lars Blumberg