A new element is written to the DOM, then after 2 seconds it is deleted. How to animate this element at the time of removal from the DOM? For example, so that the block disappears evenly as if it dissolves. Interested in the most correct and simple example.

var warningEl = document.createElement('div'); warningEl.setAttribute('class', 'warning'); var message = document.createTextNode('Какое-то сообщение'); warningEl.appendChild(message); var container = document.getElementsByClassName('container')[0]; container.appendChild(warningEl); function animate() { container.removeChild(warningEl); } setTimeout(animate, 2000); } 

css

 .warning { opacity: 1; transition-property: opacity;//какое свойство анимировать transition-duration: 2s;//длительность анимации transition-timing-function: ease;//на сколько быстро должно изменяться значение стилевого свойства для которого применяется эффект перехода } 
  • there is such a transitionend event ... speaks for itself. Subscribe to it and remove the block after the occurrence of this event - Dmytryk
  • "subscribe to it", do you have an input to use the addEventListener () method? Something does not work out. - ikar
  • yes, use addEventListener - Dmytryk
  • It does not work, see what is wrong ??? jsfiddle.net/bqymto6f/11 - ikar

1 answer 1

 var submit = document.getElementById('submit'); var container = document.getElementsByClassName('container')[0]; submit.addEventListener('click', handler); function handler() { //создаём блок с сообщением var el = document.createElement('span'); el.className= 'span'; el.innerText = 'Какой-то текст с сообщением'; container.appendChild(el); setTimeout(function(){ el.classList.add('animate'); },2000) el.addEventListener("transitionend", hide) } function hide (event){ var target = event.target; container.removeChild(target) } 
 .span { display:block; margin-top: 10px; padding: 10px; font-size: 2rem; background: #F08080; color: floralwhite; border: 1px solid red; transition-duration: 5s; opacity: 1; transition-timing-function: ease-in-out; } .animate { opacity: 0; } 
 <div class="container"> <button type="submit" id="submit">Ок</button> </div> 

  • This you set a delay of 2 seconds - Dmytryk
  • Not so formulated the question. I wanted to ask why the delay is set to add the class animate. But this is so obvious. “The transitionend event is triggered when the CSS transition is completed.” - ikar