The toast is not showing the 'hide' animation as expected

I'm struggling with making the 'hide' animation work properly for my toasts. While the 'show' animation functions correctly when the toast appears, the 'hide' animation does not display and the toast simply vanishes. Despite checking that the classes are added correctly in the logs, I've also attempted to use an 'animationEnd' event listener without success.

CSS:

  #toast-container {
    position: fixed;
    bottom: 10px;
    right: 10px;
    max-width: 25%;
    z-index: 15;
    display: flex;
    flex-direction: column;
    align-items: flex-end; /* Align items to the right */
  }

  .toast {
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    background-color: var(--page-accent-color);
    padding: 10px;
    border-radius: 10px;
    opacity: 0;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.25);
    display: inline-block;
    margin-top: 5px;
  }
  
  .toast.show {
    animation: fade-in 0.5s ease-in-out forwards;
  }

  .toast.hide {
    animation: fade-out 0.5s ease-in-out forwards;
  }

  .toast-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .toast-message {}

  @keyframes fade-in {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes fade-out {
    from {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }

JavaScript:

function showToast(title = '', message, time = 5000) {
    const toastContainer = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = 'toast';

    // Create title element if title is provided
    if (title) {
      const titleElement = document.createElement('div');
      titleElement.className = 'toast-title';
      titleElement.innerHTML = title;
      toast.appendChild(titleElement);
    }

    const messageElement = document.createElement('div');
    messageElement.className = 'toast-message';
    messageElement.innerHTML = message;
    toast.appendChild(messageElement);
    toastContainer.appendChild(toast);
    toast.classList.add('show');
    
    setTimeout(() => {
      toast.classList.add('hide');
    }, time);
  }

Answer №1

After implementing your code, I noticed that it functions correctly whether it's visible or hidden. Could it be a case of my misinterpretation, or is there potential interference from other snippets?

<!DOCTYPE html>
<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <div id="toast-container"></div>
    <button id="button">Show</button>
  </body>
  <style>
    #toast-container {
      position: fixed;
      bottom: 10px;
      right: 10px;
      max-width: 25%;
      z-index: 15;
      display: flex;
      flex-direction: column;
      align-items: flex-end; /* Align items to the right */
    }

    .toast {
      font-family: "Roboto", sans-serif;
      font-size: 16px;
      background-color: var(--page-accent-color);
      padding: 10px;
      border-radius: 10px;
      opacity: 0;
      box-shadow: 0 0 8px rgba(0, 0, 0, 0.25);
      display: inline-block;
      margin-top: 5px;
    }

    .toast.show {
      animation: fade-in 0.5s ease-in-out forwards;
    }

    .toast.hide {
      animation: fade-out 0.5s ease-in-out forwards;
    }

    .toast-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .toast-message {
    }

    @keyframes fade-in {
      from {
        opacity: 0;
      }
      to {
        opacity: 1;
      }
    }

    @keyframes fade-out {
      from {
        opacity: 1;
      }
      to {
        opacity: 0;
      }
    }
  </style>
  <script>
    function showToast(title = "", message, time = 5000) {
      const toastContainer = document.getElementById("toast-container");
      const toast = document.createElement("div");
      toast.className = "toast";

      // Create title element if title is provided
      if (title) {
        const titleElement = document.createElement("div");
        titleElement.className = "toast-title";
        titleElement.innerHTML = title;
        toast.appendChild(titleElement);
      }

      const messageElement = document.createElement("div");
      messageElement.className = "toast-message";
      messageElement.innerHTML = message;
      toast.appendChild(messageElement);
      toastContainer.appendChild(toast);
      toast.classList.add("show");

      setTimeout(() => {
        toast.classList.add("hide");
      }, time);
    }
  </script>
  <script>
    document.getElementById("button").addEventListener("click", () => {
      showToast("Title", "Message", 5000);
    });
  </script>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

What is the best way to modify and execute js and css (less) files dynamically using ajax and jQuery?

Whenever I click a button, an ajax call is triggered to load various html code into a div with the id 'main'. While displaying the html content is not an issue, integrating and applying css and js code to my current page has proven to be challeng ...

Protractor - Error: prop is undefined

Need assistance in identifying an error. Currently, I am learning Protractor and attempting to create a basic test using Page Object. //login_pageObject.js let loginContainer = function() { this.usernameInput = $("input.login-form-01"); this.passwordInp ...

Creating a weather format user interface in HTML can be accomplished by following a few

I am currently utilizing the open weather API to showcase weather data, however, I am facing difficulties in arranging the data in a format similar to the one shown below. Example output: I attempted to present the data in the following structure: ...

Implementing endless scrolling within React Native utilizing FlatList

Currently, I am working on a project that involves fetching data from an API where only 20 items are limit per page. To create a seamless scrolling experience, I am trying to load additional 20 items when the user reaches the end of the current list. Howev ...

Implementing jquery-confirm in CodeIgniter: A Step-by-Step Guide

I'm having some trouble with the jquery-confirm plugin from . Everything seems to be working fine, but when I try to delete an item, the jquery pops up an alert. However, when I click "okay", it doesn't actually delete the item. I can't figu ...

Utilize Vue.js methods to reverse the string within a paragraph using the appropriate function

Hello everyone, I've been attempting to implement a function to reverse a string within a paragraph text in vue.js. I've created a method called reverseword to reverse the words and added it to a card using :rule="reverseword()", but un ...

Recursively removing an item in React components

There is an array containing nested objects that I am working with. My goal is to successfully remove the specific element from this array. Interestingly, when I attempt to delete a non-nested element, everything works fine. However, when I try to remove a ...

Customize the appearance of the active head panel in the Bootstrap Accordion

How can I style the active position of the 'panel heading' like this: https://i.sstatic.net/75s2A.jpg I am looking to include a background color and font-weight for the active panel, as well as have the icon positioned downwards... Here is my cu ...

Tips for optimizing your webpage for mobile responsiveness

Having an issue with my webpage responsiveness on a Moto G4 device. The web development text is aligned to the right, but I want it centered. How can I achieve this for Moto G4 view? index.html This is where my full code is located: index.html <!DOC ...

Discover the process of utilizing doc.getElementbyClassName to determine if any of its elements are blank

On my HTML invoice table, I sometimes have empty elements that cause the row to misalign. To fix this, I want to add whitespace if an element is empty. Here is the structure of the table: <div class="invoiceTable"> <div class="titles2" style=" ...

Display a section of a webpage with the CSS styles hidden

I encountered an issue while attempting to print a section of my website. Despite having CSS information embedded in my HTML file, the properties are not being displayed. Do you have any solutions for this problem? var content = document.getElementById("d ...

Combining Import and Require in a Node JS File

Having some trouble with the normalize-url package. It needs to be imported instead of required since it's not supported in ES module. I tried to work around this by adding some code I found online, but it doesn't seem to be fixing the issue for ...

Angular view fails to update after form submission when using ngDialog to change the scope

After starting my Angular journey, I decided to challenge myself by creating a comprehensive todo app for educational purposes. I seem to be missing something pretty basic, although I can't quite put my finger on it. It seems like there might be an is ...

Discovering access to this.$i18n.locales from store getter in Nuxt, i18n, and Vuex

Currently, I am constructing a web application utilizing Nuxt v2.15 and @nuxtjs/i18n v7.2 while employing Vuex for state management. Within my global state, I aim to develop a getter that retrieves a value reliant on this.$i18n.locale. How can I effective ...

FluentPlayer with RMTP integration

Experiencing challenges in integrating Flowplayer with RTMP for smooth playback. Here is the current configuration: JS $f("flashFallback", "/uploadedFiles/flowplayer.commercial-3.2.7.swf", { key: '#mykey', clip: { url: 'my ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Video streaming platform without the need for javascript and plugins

Is it feasible to watch Youtube videos without relying on javascript and plugins, exclusively using HTML5 or a similar alternative? ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...