Synchronize the animation of the elements when inserting into the DOM

Asked

Viewed 26 times

2

It is possible to insert an animated element in the DOM synchronized? i.e., when inserting 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>

1 answer

1


It is possible to define the animation for none and using setTimeout for after a little delay, empty the animation. When emptying, it will inherit what was initially set in CSS, making all .pulse 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.