Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create '@-Keyframe' CSS animations?

I have a requirement to rotate a div and stop at a particular position ( The value will be received from the server).

I tried native JS to rotate and stop but it is eating up my CPU big time.

I can rotate with CSS animation but I need to create a class which will dynamically describe where to stop the animation. Something like

@-webkit-keyframes spinIt {     100% {         -webkit-transform: rotate(A_DYNAMIC_VALUE);     } } @-moz-keyframes spinIt {     100% {         -webkit-transform: rotate(A_DYNAMIC_VALUE);     } } 

Here is one reference

http://jsfiddle.net/bVkwH/8/

Thanks in Advance

like image 269
Jagadeesh J Avatar asked Aug 28 '13 07:08

Jagadeesh J


1 Answers

You can insert stylesheet rules dynamically to override previous styles in the head. This helps avoid adding yet another library for a single task.

var style = document.createElement('style'); style.type = 'text/css'; var keyFrames = '\ @-webkit-keyframes spinIt {\     100% {\         -webkit-transform: rotate(A_DYNAMIC_VALUE);\     }\ }\ @-moz-keyframes spinIt {\     100% {\         -webkit-transform: rotate(A_DYNAMIC_VALUE);\     }\ }'; style.innerHTML = keyFrames.replace(/A_DYNAMIC_VALUE/g, "180deg"); document.getElementsByTagName('head')[0].appendChild(style); 
like image 186
Alex Grande Avatar answered Sep 28 '22 18:09

Alex Grande