JSFiddle - React, Tailwind, and code Playground
by cent cent
HTML
<div id="box"></div>
<div id="update-box">Run Another Animation</div>
CSS
@-webkit-keyframes rotate {
0% {-webkit-transform: rotate(-10deg);}
100% {-webkit-transform: rotate(10deg);}
}
body { text-align: center; }
#box {
height: 100px;
width: 100px;
background-color: blue;
-webkit-animation-duration: 1s;
-webkit-animation-timing-function: linear;
-webkit-animation-name: "rotate";
margin: 30px auto;
}
#update-box {
border: 3px solid black;
background: #efefef;
font-weight: bold;
cursor: pointer;
padding: 10px;
margin: 30px auto;
display: inline-block;
}
#update-box:hover {
background: black;
color: white;
}
JavaScript
function getCSS(){
var styles = document.styleSheets;
var value = '';
for(var i=0; i<styles.length; i++){
value += 'styles['+i+']:\n---------\n';
for(prop in styles[i])
value += '--->property: '+prop+'\nvalue: '+styles[i][prop]+'\n';
}
alert(value);
}
getCSS();
// search the CSSOM for a specific -webkit-keyframe rule
function findKeyframesRule(rule){
// gather all stylesheets into an array
var ss = document.styleSheets;
// loop through the stylesheets
for (var i = 0; i < ss.length; ++i) {
// loop through all the rules
for (var j = 0; j < ss[i].cssRules.length; ++j) {
// find the -webkit-keyframe rule whose name matches our passed over parameter and return that rule
if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && ss[i].cssRules[j].name == rule)
return ss[i].cssRules[j];
}
}
// rule not found
return null;
}
// remove old keyframes and add new ones
function change(anim){
// find our -webkit-keyframe rule
var keyframes = findKeyframesRule(anim);
// remove the existing 0% and 100% rules
keyframes.deleteRule("0%");
keyframes.deleteRule("100%");
// create new 0% and 100% rules with random numbers
keyframes.insertRule("0% { -webkit-transform: rotate("+randomFromTo(-360,360)+"deg); }");
keyframes.insertRule("100% { -webkit-transform: rotate("+randomFromTo(-360,360)+"deg); }");
// assign the animation to our element (which will cause the animation to run)
document.getElementById('box').style.webkitAnimationName = anim;
}
// begin the new animation process
function startChange(){
// remove the old animation from our object
document.getElementById('box').style.webkitAnimationName = "none";
// call the change method, which will update the keyframe animation
setTimeout(function(){change("rotate");}, 0);
}
// get a random number integer between two low/high extremes
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) +...