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?

RickyAYoder
  • 963
  • 1
  • 13
  • 29

2 Answers2

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

Carlo Cannas
  • 3,206
  • 19
  • 22
  • Do you know any down-to-earth tutorials on using CSSOM in JavaScript? Like a blog post or tutorial site? – RickyAYoder Dec 05 '13 at 19:06
  • I searched a bit, but I didn't found much, this article is the best I found: http://css-tricks.com/controlling-css-animations-transitions-javascript/. It makes examples exactly with animation rules. – Carlo Cannas Dec 05 '13 at 19:39
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

Community
  • 1
  • 1
adam187
  • 3,193
  • 21
  • 15