var elm = document.querySelector('.to-animate');
var op = document.querySelector('.output');
var animName = "shake-up-down",
animDuration = "3s",
animTiming = "linear",
animFillMode = "forwards",
animIteration = "3";
var ruleText = "0% {transform: translateY(0px);}";
ruleText += "25% {transform: translateY(10px);}";
ruleText += "75% {transform: translateY(-10px);}";
ruleText += "100% {transform: translateY(0px);}";
function addCSSAnimRule(sheet, name, rules, index) {
if ("insertRule" in sheet) {
sheet.insertRule("@keyframes " + name + "{" + rules + "}", index);
} else if ("addRule" in sheet) {
sheet.addRule("@keyframes " + name, rules, index);
}
}
function applyAnimation(elm, name, duration, timing, iteration, fillmode) {
elm.style["animation"] = name + " " + duration + " " + timing + " " + iteration + " " + fillmode;
}
addCSSAnimRule(document.styleSheets[0], animName, ruleText, 0);
applyAnimation(elm, animName, animDuration, animTiming, animIteration, animFillMode);
elm.addEventListener("animationstart", function(e) {
op.textContent = "Animation " + e.animationName + " has started.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
elm.addEventListener("animationend", function(e) {
elm.removeAttribute("style");
op.textContent += "\nAnimation " + e.animationName + " has ended.";
op.textContent += "\n\nElement's Outer HTML: \n";
op.textContent += elm.outerHTML;
op.textContent += "\n\n------------------------------------------------------------------------------";
});
.to-animate {
height: 100px;
width: 100px;
margin: 10px;
border: 1px solid red;
}
<div class='to-animate'></div>
<pre class='output'></pre>