First, get rid of these moz
prefixes everywhere, Firefox supports unprefixed animation since years, so do every browsers. (besides, it's style.MozXXX
)
Then, style.animationName
should be the animation's name (yes), and your animation is called "pop
", not "pop 2s
".
2s
would be a valid value for style.animationDuration
:
var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.setAttribute(
'style',
'opacity:' + '0;'
);
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode('@keyframes pop {'+
'0% { opacity:0; }'+
'50% { opacity:1; }'+
'100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
cue.style.animationName = 'pop';
cue.style.animationDuration = '2s';
<div id="appContainer"></div>
pop 2s
looks more like the shorthand animation
property:
var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.setAttribute(
'style',
'opacity:' + '0;'
);
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode('@keyframes pop {'+
'0% { opacity:0; }'+
'50% { opacity:1; }'+
'100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
cue.style.animation = 'pop 2s';
<div id="appContainer"></div>
But I can't help to note that if you are on the way to write dynamic stylesheets, it makes very little sense to set your element's inline styles; rather set these styles inside your stylesheet too:
var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode( '' +
'#cue {' +
' opacity: 0;'+
' animation: pop 2s infinite;'+
'}' +
'@keyframes pop {'+
' 0% { opacity:0; }'+
' 50% { opacity:1; }'+
' 100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
<div id="appContainer"></div>