saginadir
9/28/2016 - 2:40 PM

CSS animations on the fly generation with JavaScript

CSS animations on the fly generation with JavaScript

// We are creating a new style tag
let newStyleSheet = document.createElement("style");

// Appending the style tag to the head.
document.head.appendChild(newStyleSheet);

// Writing to the style sheet some css rules including keyframes and the animation class
newStyleSheet.appendChild(document.createTextNode(`
@keyframes my-fun-keyframes {
    /* My keyframes for the animation I want to create */
}

.animate {
    animation: my-fun-keyframes 1s infinite;
}
`));

// el is the element we want to animate
el.classList.add("animate");

// Good! now el will animate according to the animation we created above!