I
I
Ivanq2015-10-09 19:03:26
css
Ivanq, 2015-10-09 19:03:26

Add CSS animation via JavaScript?

Hello Toaster!
I'm trying to figure out the problem - how to add CSS animation through JavaScript anywhere in the code? I can paste the CSS animation code by hand:

@keyframes anim {
    0% {
        background-color: yellow;
    }
    100% {
        background-color: green;
    }
}
#anim {
    animation: anim 2s ease;
}

And correspondingly
document.getElementById("anim").style.animation = "anim 2s ease";

How to add animation: understandable, but @keyframes?
PS Preferably without jQuery, Mootools, etc.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Dyrkov, 2015-10-09
@Ivanq

To do this, use css classes
Let's say we have a set of animations and classes with them, in animation.css

@keyframes anim {
    0% {
        background-color: yellow;
    }
    100% {
        background-color: green;
    }
}
.main-animation {
    animation: anim 2s ease;
}

in js code, we need to add or remove an animation class from the element we want to animate
document.querySelector('.box').className="main-animation";
//если надо убрать анимацию то удаляем класс и всё

This method is more practical (I do not recommend doing it differently), everyone does it that way.
Use js to work with DOM and provide animation with CSS Animations

E
Evgeny Petrov, 2015-10-09
@EvgenZZ

better use Animate.css

O
Orzubek Rakhimov, 2015-10-09
@orzubek


Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question