How to dynamically create ‘@-Keyframe’ CSS animations?

You can insert stylesheet rules dynamically to override previous styles in the head. This helps avoid adding yet another library for a single task.

var style = document.createElement('style');
style.type="text/css";
var keyFrames="\
@-webkit-keyframes spinIt {\
    100% {\
        -webkit-transform: rotate(A_DYNAMIC_VALUE);\
    }\
}\
@-moz-keyframes spinIt {\
    100% {\
        -webkit-transform: rotate(A_DYNAMIC_VALUE);\
    }\
}";
style.innerHTML = keyFrames.replace(/A_DYNAMIC_VALUE/g, "180deg");
document.getElementsByTagName('head')[0].appendChild(style);

Leave a Comment