CSS Animation & Keyframes
by black strings
October 26, 2022
HTML
<div id="main-container">
</div>
<!-- To wire up the element to the anaimation, simply add the style tag animation-name: <keyframe-name> -->
<!-- exmple of how the dynamic generated code looks like -->
<!--
<div class="parent">
<div class="child">
bounce
</div>
</div>
-->
CSS
body {
background-color: #000000;
}
div.parent {
display: inline-block;
}
div.child {
color: white;
}
/**
to see all properties
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations
*/
.default-animation-spec {
animation-duration: 4s;
animation-delay: 0;
animation-fill-mode: backwards;
animation-direction: normal;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes bounce {
0%{transform: scale(.5)}
50%{transform: scale(.7)}
100% {transform: scale(1)}
}
@keyframes left-to-right {
0% {transform: translateX(0%)}
100% {transform: translateX(10%)}
}
@keyframes down-to-top {
0% {transform: translateY(0px)}
10% {transform: translateY(25px)}
20% {transform: translateY(25px)}
30% {transform: translateY(0px)}
}
.circle-bg {
display: table-cell;
vertical-align: middle;
height: 100px;
width: 100px;
background-color: #001110;
border-radius: 50%;
text-align: center;
color: white;
}
JavaScript
const mc = document.getElementById('main-container');
const itemName = [
'bounce','left-to-right','down-to-top'
]
const items = [];
itemName.forEach(itemName => {
items.push({animName: itemName});
});
items.forEach(item => {
const parent = document.createElement('div');
parent.className = 'parent';
const child = document.createElement('div');
child.innerHTML = item.animName;
// defines the animation duration, speed, delay
child.className = 'default-animation-spec circle-bg';
// when the style is applied, the animation will start
child.style = `animation-name: ${item.animName}`;
parent.appendChild(child);
mc.appendChild(parent);
});