1

For the animation library I'm making, I want transitions and animations.

Transitions were simple. I can easily access the transition property from the style property of an element object:

   document.body.style['-webkit-transition'] = "background 1s";
   document.body.background = "#f00";

I know that in CSS, there are 2 parts to animations, @-keyframes and then calling the actual animation.

How do I assign an @-keyframe rule through pure JavaScript?

It wouldn't be something like transitions, because @-keyframe rules aren't applied directly to elements.

An alternative to this would be to dynamically create an @-keyframes rule through JavaScript from a string, and append it to a temporary stylesheet. Kind of sloppy, which is why I'm wondering how to do it directly through the DOM.

Is there a way? From what I have seen on some other sites, you can play animations and stop them at certain keyframes, but how do you create the animations themselves?

2 Answers 2

1

You have to use the CSSOM, which allows you (among the other things) to manipulate the stylesheets loaded in a document. First of all, you need a stylesheet loaded in your document, where you'll add the @keyframe rules. If you haven't one, you can dynamically create a style HTML element and append it to the head. Then you have to obtain the instance of the CSSStyleSheet interface that represent the stylesheet, you can either retrieve the sheet property of the style (or link) HTML element, or take it from the list available at document.styleSheets.

Once you have the object you can simply call the method insertRule on it, passing the whole rule as a string and for second parameter a number indicating the position (before which rule will be added this one).

If you have to manipulate further the animations, give a look at the APIs: http://www.w3.org/TR/css3-animations/#dom-interfaces http://www.w3.org/TR/DOM-Level-2-Style/css.html

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know any down-to-earth tutorials on using CSSOM in JavaScript? Like a blog post or tutorial site?
I searched a bit, but I didn't found much, this article is the best I found: css-tricks.com/…. It makes examples exactly with animation rules.
0

I haven't seen any javascript api solution but it is possible with css styles generated from javaScript.

Check out http://krazyjakee.github.io/jQuery.Keyframes/ if you using jQuery.

If you whant pure javascript solition then take a look at this post

1 Comment

Yes. This involves appending the animation as a string into a style tag. Not what I wanted, but I can do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.