+ 3
How to change CSS keyframe animations with JS?
Being new Web Development, I want to know if I can the CSS keyframe animations with JS.
4 Réponses
+ 5
thanks maz, visph, and calvin
+ 10
You can, but...
1) If the animation is complex, you can use the setTimeout method to replace the keyframes.
2) It is harder change a keyframes in JS, but... you might use a "trick".
Declare your CSS keyframes and inside the Javascript code, assign the animation name in this way:
element.style.animation = "name_of_your_animation
speed
animation_timing
animation_duration";
Example:
element.style.webkitAnimation =
"dog 1s linear infinite";
element.style.animation =
"dog 1s linear infinite";
When you want to remove the animation, you could just use a "none" value, like:
element.style.webkitAnimation = "none";
element.style.animation = "none";
Anyway, if you want to declare/change a CSS keyframes inside Javascript (not recommended), take a look here:
https://blogs.msdn.microsoft.com/msdn_answers/2013/11/04/part-i-using-javascript-to-set-keyframes-in-css-animations-windows-store-apps-ie/
https://stackoverflow.com/questions/3328933/set-the-webkit-keyframes-from-to-parameter-with-javascript
Source: Just my tips, always used this method to work with CSS keyframes in Javascript, if someone know better solutions, let me know. :3
+ 3
Css animations provide specific useful event listener that you can use to help you in handling them with JS:
http://callmenick.com/post/listen-for-css-animation-events-with-javascript
https://www.sitepoint.com/css3-animation-javascript-event-handlers/
https://developer.mozilla.org/fr/docs/Web/CSS/Animations_CSS/Utiliser_les_animations_CSS
https://developer.mozilla.org/fr/docs/Web/API/GlobalEventHandlers/onanimationend
+ 1
If the keyframes is put in separated style tag with an id attribute, you could possibly make the keyframes values changed by Javascript.
Check out the sample code here..
https://code.sololearn.com/WYF6Qaj1FLY6/?ref=app