Synchronize animation of elements when inserting in DOM

2

Is it possible to insert an animated element in DOM synchronously? that is, when entering the current state is maintained and not reset as in the example below ...

function add() {
	let ctn = document.getElementById('ctn');
  
  ctn.insertAdjacentHTML('beforeend', '<div class="pulse">teste</div>');
}
#ctn {
  width: 100px;
  background-color: green;
}
.pulse {
  animation: pulse 0.7s infinite;
  padding: 10px;
  margin: 0 auto;
  display: table;
  animation-direction: alternate;
  -webkit-animation-name: pulse;
  animation-name: pulse;
}

@-webkit-keyframes pulse {
  0% {
    -webkit-background-color: rgba(0,0,0,0);
  }
  100% {
    -webkit-background-color: rgba(255,255,255,0.5);
  }
}

@keyframes pulse {
  0% {
    background-color: rgba(0,0,0,0);
  }
  100% {
    background-color: rgba(255,255,255,0.5);
  }
}
<div id="ctn">
  <div class="pulse">teste</div>
</div>
<button onclick="add()" >
  Inserir
</button>
    
asked by anonymous 01.04.2018 / 23:44

1 answer

1

It is possible to set animation to none and using setTimeout to after a small delay , empty animation . When empty, it will inherit what was initially defined in the CSS, causing all .pulse to start at the same time.

See example:

function add() {
	let ctn = document.getElementById('ctn');
  
  ctn.insertAdjacentHTML('beforeend', '<div class="pulse">teste</div>');
  
  let pulse = document.body.querySelectorAll(".pulse");
  
  pulse.forEach(item=>{
     item.style.animation = "none";
  });
  setTimeout(function(){
     pulse.forEach(item=>{
        item.style.animation = "";
     });
  }, 100);
  
}
#ctn {
  width: 100px;
  background-color: green;
}
.pulse {
  animation: pulse 0.7s infinite;
  padding: 10px;
  margin: 0 auto;
  display: table;
  animation-direction: alternate;
  -webkit-animation-name: pulse;
  animation-name: pulse;
}

@-webkit-keyframes pulse {
  0% {
    -webkit-background-color: rgba(0,0,0,0);
  }
  100% {
    -webkit-background-color: rgba(255,255,255,0.5);
  }
}

@keyframes pulse {
  0% {
    background-color: rgba(0,0,0,0);
  }
  100% {
    background-color: rgba(255,255,255,0.5);
  }
}
<div id="ctn">
  <div class="pulse">teste</div>
</div>
<button onclick="add()" >
  Inserir
</button>
    
02.04.2018 / 00:34