Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically modify webkit animation with javascript

I would like to use webkit animation with @-webkit-keyframes but being able to dynamically modify the values on the rule, so that the animation is not static. All the samples I found use a static @-webkit-frames, is there a way to customize with Javascript?

like image 258
Arnaud Avatar asked Mar 22 '10 21:03

Arnaud


People also ask

Can JavaScript add animation?

Animation CodeJavaScript animations are done by programming gradual changes in an element's style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.

Does CSS animation use JavaScript?

CSS allows animation of HTML elements without using JavaScript or Flash! In this chapter you will learn about the following properties: @keyframes.

Is WebKit used for animation?

WebKit now supports explicit animations in CSS. As a counterpart to transitions, animations provide a way to declare repeating animated effects, with keyframes, completely in CSS.

Which browser would support the WebKit animation parameters?

Only WebKit (Safari), and not Chromium, based browsers supports the -webkit-animation media feature.


2 Answers

I had to create a new style rule in the loaded style sheets. Seems to work great in chrome 5.0.342.9 beta (at least)

var lastSheet = document.styleSheets[document.styleSheets.length - 1];
lastSheet.insertRule("@-webkit-keyframes " + newName + " { from { top: 0px; } to {top: " + newHeight + "px;} }", lastSheet.cssRules.length);

and then assign the animation name using element.style

element.style.webkitAnimationName = newName;
like image 185
case nelson Avatar answered Oct 21 '22 15:10

case nelson


I wish I could credit for this, but here's a link to someone who managed to modify an existing animation, as opposed to creating a new animation.

http://gitorious.org/webkit/webkit/blobs/438fd0b118bd9c2c82b6ab23956447be9c24f136/LayoutTests/animations/change-keyframes.html

I've ran this to verify that it does, indeed, work.

EDIT

So that link is dead and I don't trust Gitorious to maintain URLS anymore so here's a link to a JSFiddle I created to answer a similar question: http://jsfiddle.net/russelluresti/RHhBz/3/

This contains script to find an existing animation, update its values, and assign it to an element to make the animation occur. I have tested this in Chrome 18 and Safari 5.1

like image 36
RussellUresti Avatar answered Oct 21 '22 16:10

RussellUresti