jeudi 31 janvier 2019

How can I restart a CSS animation with random values in a loop?

I have an element which is randomly animated with CSS and JS with the help of CSS custom properties in the following way:

CSS:

: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);
  }
}

JS:

var my-element = document.querySelector('#my-element');

function setProperty(number) {
  my-element.style.setProperty('--animation-name', 'vibrate-'+ number);
}

function changeAnimation() {
  var number = Math.floor(Math.random() * 3) + 1;
  setProperty(number);
  /* restart the animation */
  var clone = my-element.cloneNode(true);
  my-element.parentNode.replaceChild(clone, my-element);
}

my-element.addEventListener('animationend', changeAnimation, false);

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 – as I am quite a newbie to JS;-) 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? Thanks in advance!

Stefan




Aucun commentaire:

Enregistrer un commentaire