Home Web Front-end CSS Tutorial How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

Dec 09, 2024 pm 10:57 PM

How to Dynamically Set WebKit Keyframe Animation Rotation Values Using JavaScript?

Dynamic Keyframe Values: Using JavaScript Variables in CSS

Question:

How can you dynamically set the rotation values of a Webkit keyframe animation using JavaScript variables?

Answer:

In CSS, you cannot directly insert JavaScript variables into keyframe animations. To achieve this, you need to create the CSS rules through JavaScript and insert them into the CSS Object Model (CSSOM).

Consider the following sample code:

@-webkit-keyframes rotate {
    0% {-webkit-transform: rotate(-10deg);}
    100% {-webkit-transform: rotate(10deg);}
}

#dog{
/*irrelevant settings*/
-webkit-animation: rotate 5s infinite alternate ease-in-out;
}
Copy after login

To dynamically set the rotation values, you can write a JavaScript function:

// Assume var dogValue = "20deg";
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
var keyframesRule = `@-webkit-keyframes rotate {
    0% {-webkit-transform: rotate(-${dogValue});}
    100% {-webkit-transform: rotate(${dogValue});}
}`;
styleElement.appendChild(document.createTextNode(keyframesRule));
document.head.appendChild(styleElement);
Copy after login

This code creates a new