Dynamic WebKit Animations

Dynamic WebKit Animations

WebKit animations are a great tool if you want to plot out a predetermined set of keyframes.  As web applications grow in complexity, more flexibility and control is needed in order to take advantage of these features.  One technique you can do is animate based on style changes and use timers to chain animations.  A major issue with this is that -webkit-animation-duration is a guideline and not a guaranteed thing.  This could result in your timer getting fired before the animation is complete.

Unfortunately, there isn’t a graceful way to dynamically create these animations.  What you need to do is manually construct the CSS rule and insert it into the style sheet.

var animationName = "myAnimation";
var fromStyle = {
"-webkit-transform": "scale(0)";
};
var toStyle = {
"-webkit-transform": "scale(1)";
};

var key, fromStr = "", toStr = "";

for(key in fromStyle) {
fromStr += key + ": " + fromStyle[key] + "; ";
}
for(key in toStyle) {
toStr += key + ": " + toStyle[key] + "; ";
}

var lastSheet = document.styleSheets[document.styleSheets.length - 1];
lastSheet.insertRule("@-webkit-keyframes " + animationName+ " { from { "+fromStr
+ " } to { " + toStr + " } }", lastSheet.cssRules.length);

You can then assign this animation to your element:

element.style.webkitAnimationName = animationName;

 

3 Comments

  1. No offense, but i suggest adding a facebook like button for the blog!

    Reply
  2. Done – Thanks for the suggestion!

    Reply
  3. No offense, but you rock!

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *