2

I'm creating CSS animations on the fly, so I need to insert a CSS timing function into my document. As in:

@-webkit-keyframes slide 
{
    from {
    -webkit-transform: translateX(-100px) translateY(-100px);
    -webkit-animation-timing-function: ease-in;
    }

    33% {
    -webkit-transform: translateX(-100px) translateY(-50px);
    -webkit-animation-timing-function: linear;
    }

    66% {
    -webkit-transform: translateX(-50px) translateY(0px);
    -webkit-animation-timing-function: linear;
    }


    to {
    -webkit-transform: translateX(0px) translateY(0px);
    -webkit-animation-timing-function: ease-out;
    }
}

Any idea how to pull this off (the insertion) using Javascript? I can add regular classes without any trouble, but this seems to be a special case.

1 Answer 1

3

Actually, it's no different from adding any other style rule to a stylesheet:

var selector = "@-webkit-keyframes slide";
var rule = "{   from {  -webkit-transform: translateX(-100px) translateY(-100px);   -webkit-animation-timing-function: ease-in; }   33% {   -webkit-transform: translateX(-100px) translateY(-50px);    -webkit-animation-timing-function: linear;  }   66% {   -webkit-transform: translateX(-50px) translateY(0px);   -webkit-animation-timing-function: linear;  }   to {    -webkit-transform: translateX(0px) translateY(0px); -webkit-animation-timing-function: ease-out;    }       }";

document.styleSheets[0].insertRule(selector + rule, 0);

Note that the above DOM manipulation is WebKit (and FireFox) specific. You'd need to add some logic to s/insertRule/addRule for IE.

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

2 Comments

If you're going to do stylesheet injection like this, then why not just do the animation using JavaScript?
Try both side by side, and you'll have your answer. CSS animation in webkit (especially on iOS) is quite a thing to behold. It's orders of magnitude smoother to the eye, which makes sense considering that it takes advantage of hardware acceleration to do its thing.

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.