transition is not working correctly when a new element is added to the dom

You having to use a setTimeout is because of how javascript works with the event loop. Here is a really good video explaining a basic fundamental thing that you need to know about javascript. (Hey, I’ve been working with web development for five years, but been using javascript for 20, and just got to know about this this summer.)

Jake Archibald: In The Loop

If you don’t want to use a timeout, you can instead use an animation. The downside is that it’s hard to control specific times. If you start with opacity 0 and then have opacity 1 at 15%, that will create slower fade ins for longer toast durations.

function flashToast(msg, duration) {
  duration = duration || 3000;

  const toastElement = document.createElement("p");
  toastElement.innerHTML = msg;

  toastElement.classList.add("toast");
  
  // Added 
  toastElement.style.setProperty("--duration", duration + "ms");

  document.body.appendChild(toastElement);

  setTimeout(function() {
    document.body.removeChild(toastElement);
  }, duration);
}
.toast {
  display: inline-block;
  font-size: 1.2rem;
  padding: 0.8em 1em;
  border-radius: 5rem;
  color: #eaeaea;
  background: #606060;
  background: rgba(96, 96, 96, 0.7);
  position: absolute;
  bottom: 2%;
  left: 50%;
  transform: translate(-50%, -50%);
  
  /* NEW */
  animation: fade var(--duration) linear;
}

@keyframes fade {
  0%   {opacity: 0;}
  15%  {opacity: 1;}
  85%  {opacity: 1;}
  100% {opacity: 0;}
}
<button onclick="flashToast('Toast!')">Show toast</button>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top