I have an element which is randomly animated with CSS and JS with the help of CSS custom properties in the following way:
var myElement = document.querySelector('#my-element');
function setProperty(number) {
myElement.style.setProperty('--animation-name', 'vibrate-' + number);
}
function changeAnimation() {
var number = Math.floor(Math.random() * 3) + 1;
setProperty(number);
/* restart the animation */
var clone = myElement.cloneNode(true);
myElement.parentNode.replaceChild(clone, myElement);
}
myElement.addEventListener('animationend', changeAnimation, false);
#my-element {
width: 50px;
height: 50px;
background: #333;
}
:root {
--animation-name: vibrate-1;
}
#my-element {
animation: 3.3s 1 alternate var(--animation-name);
}
@keyframes vibrate-1 {
0% {
opacity: 0;
transform: scale(0.95);
}
50% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(0.9);
}
}
@keyframes vibrate-2 {
0% {
opacity: 0;
transform: scale(0.5);
}
50% {
opacity: 1;
transform: scale(0.9);
}
100% {
opacity: 0;
transform: scale(0.5);
}
}
@keyframes vibrate-3 {
0% {
opacity: 0;
transform: scale(0.3);
}
50% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(0.8);
}
}
<div id="my-element"></div>
The idea behind is to have a set of animations which switch on each animation’s end randomly to another one. (that for the opacity in the end is always 0 to make a smooth invisible switch.)
Now, surprisingly, this code above runs just fine, except that it does only once and then stop.
I now there are JS loop techniques but I have no idea how to exactly implement them inside this workflow.
Can someone help me?