Is there a way to detect the completion of the fadeout animation before calling a function?

I am trying to create a toast message using jQuery.

When the "show" class is appended to the div, I want the toast message to fade in and then fade out after a few seconds.

Once the fade-out animation is complete, I need to remove the "show" class.

This is my first attempt at writing this code.

var showToast = function(msg) {
     clearTimeout(window.timeoutToast);

     $("toastDiv p").html(msg);
     $("toastDiv").addClass("show");
     window.timeoutToast = setTimeout(function() {
         $("toastDiv").removeClass("show")
     }, 3000);
 };

I have tried calling clearTimeoutFunc and removing the show class.

However, if I click multiple times quickly, the toast message fades out and then immediately reappears.

I also attempted to use $("toastDiv").on("animationed webkitAnimationEnd oAnimationEnd MSAnimationEnd", function() { ... }) but the function was triggered when the fade-in animation finished.

Here is my HTML code:

<div class="toastDiv">
    <p class="txt_toast">blablabla</p>
</div>

And here is my CSS:

.toastDiv.show{
     visibility: visible;
     -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
     animation: fadein 0.5s, fadeout 0.5s 2.5s;
}

Please help me fix my code...

Answer №1

Here is an improved solution using only JavaScript:

var displayToast = function(message) {
  clearTimeout(window.timeoutToast);

  $(".toastMessage p").html(message);
  $(".toastMessage").addClass("show");

  $(".toastMessage").on('animationend', function(event) {
    var animationName = event.originalEvent.animationName;
    if (animationName === 'fadeout') {
      $(".toastMessage").removeClass("show");
    }
  });
};

displayToast('Hello, toast!');
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeout {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

.toastMessage {
  visibility: hidden;
}

.toastMessage.show{
     visibility: visible;
     -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
     animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toastMessage">
  <p class="toastText">sample message</p>
</div>

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

Turn off smooth scrolling in Bootstrap 5 using HTML and CSS techniques

On my website, I have implemented anchor links that activate smooth scrolling when clicked, thanks to the Bootstrap feature. However, the unique layout of my website requires me to turn off smooth scrolling in either the HTML or CSS code. I appreciate an ...

What is the best way to obtain the present date in Nuxt directly from the server?

While conducting code tests, I realized that I required the current time from the server to run the tests effectively. In JavaScript, you can easily obtain the current date on the client side using the command: new Date();. However, when working with Nuxt ...

What is the best way to adjust the height of a div element according to the width of its child element?

I am facing an issue with two nested divs, where the inner one is absolutely positioned inside the outer one. I want the height of the outer div to adjust dynamically according to changes in the width of the inner div. To better illustrate the problem, I h ...

Is it possible to adjust the position of a h2 heading on a particular webpage using CSS?

There is a situation where multiple pages contain h elements nested inside a standard container div class. When trying to edit a specific h2 element in a specific page using CSS, simply editing the h2 or the container does not work. Other methods attempte ...

The compatibility between Babel 7 and the preset-es2015 is not very reliable

After reading this useful tutorial on implementing server-side rendering with create-react-app, I attempted to execute the following code snippet: require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

Using jQuery Mobile to dynamically load content into a specific div element

Jquery Mobile operates by seizing control of a page and fetching content to inject into it. However, this poses an issue when attempting to inject additional content into the page. In my setup, I have an index.html and a page2.html file. I am configuring ...

HTML5 Dragend event failed to trigger in Firefox

While working on my project, I encountered an issue where the 'dragend' event is not fired in Firefox 22.0 on Ubuntu but works perfectly fine in Chrome. I have written a logic to make changes on drag start and revert them if drop fails, triggered ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Issues with radio buttons not functioning or being able to be selected in Internet Explorer

My radio buttons are functioning perfectly in Chrome, Firefox, and Safari, but for some reason, they are not selectable in Internet Explorer (Version 7). Any suggestions on how I can resolve this issue? HTML: <label> <input type="radio" name ...

Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet Here is the code snippet of what I have tried so far: $("div#DivDet").scroll(function () { // Still trying to figure out what ...

Attempting to transmit checkbox data in jade

I am currently developing an app with Express, Node.js, and Mongo. I have encountered an issue while passing checkbox values to my database. My goal is to only pass the values of checked checkboxes back to the database. In my index.jade file, I attempted ...

Having issues with templateURL not working in AngularJS routeProvider

I've been experimenting with ngRoute and I'm facing an issue with templateURL not working as expected. The functionality works perfectly except for when I attempt to use templateURL. Here are the 4 files involved: test.html <p>{{test}}&l ...

What is the process for adjusting the color of a mat-divider?

Has anyone been successful in changing the color of mat-divider? I attempted the following but had no luck: component.html <mat-divider class="material-devider"></mat-divider> component.scss .material-devider { color: red } ...

I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble. I faced an issue when I created a new component in the directory and placed my Button component there. Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define th ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

Using jQuery to retrieve the element that triggers a function

Greetings! I am new to using jQuery and I am looking to access an element that I have clicked on. My goal is to navigate to neighboring elements and retrieve their values. <td>21</td> <td>Peter</td> <td>Admin</td> <t ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

React: Issue with input values not correctly updating across multiple fields when changing state toggles

I am working on a React component that needs to update input values for multiple players independently. However, I am facing an issue where toggling a state causes the first input's value to incorrectly propagate to all other inputs. Additionally, cle ...

Minimize the gap between legend text and icon in Highchart

Is there a way to decrease the space between the number and icon? I am currently working with Angular 8 and Highchart. Below is the configuration of the chart legend. https://i.stack.imgur.com/0dL7y.jpg this.legend = { align: 'center', verti ...