0

How can a JavaScript statement be called after another has finished? The container element should only be removed from the DOM after the CSS transition is finished. Is this possible using callback functions, or would a custom event need to be created? It would be best to know how without the use of jQuery. Is it possible to do using ES5 without Promises?

var myContainer = document.getElementById("my-container");
myContainer.style.opacity = 1;
myContainer.style.transition = "opacity 1s";

var myButton = document.getElementById("myButton");
myButton.addEventListener('click', hideContainer);

function hideContainer() {

  // Set container opacity to 0
  myContainer.style.opacity = 0;

  // Only execute once opacity has reached 0.
  document.body.removeChild(myContainer);

}
crayden
  • 2,130
  • 6
  • 36
  • 65
  • `without Promises` Why no Promises? Promises are wonderful, and can be polyfilled – CertainPerformance May 14 '18 at 03:20
  • Possible duplicate of [Is there a callback on completion of a CSS3 animation?](https://stackoverflow.com/questions/6186454/is-there-a-callback-on-completion-of-a-css3-animation) – 31piy May 14 '18 at 03:22
  • 1
    If you know the transition is 1s, why not just use a `setTimeout`? – jhpratt May 14 '18 at 03:24

1 Answers1

0

you need to listen to animation end events animationend and remove the dom after it complete

myContainer.addEventListener("animationend", function(){
    document.body.removeChild(myContainer);
});
Nerdroid
  • 13,398
  • 5
  • 58
  • 69