Jihyun Moon
Jihyun Moon

Reputation: 25

How can I detect to finish fadeoutAnim and call function?

I am using jquery and i want to make like toast message.

so, if "show" class append to div, the toast message would be fade in, and after some seconds fade-out.

I have to finished fade-out anim, remove the "show" class.

It is my first code.

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

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

I tried call clearTimeoutFunc, and removeClass show class.

but if I clicked multiple fastly, the toastMessage was fade-out, and show in a blink....

Also I tried $("toastDiv").on("animationed webkitAnimationEnd oAnimationEnd MSAnimationEnd", function() { ... }) but, when the fade-in anim finished, the function was called.

first, my html code

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

and 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 fix my code...

Upvotes: 0

Views: 60

Answers (1)

giuseppedeponte
giuseppedeponte

Reputation: 2391

Edited for JS only solution:

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

  $(".toastDiv p").html(msg);
  $(".toastDiv").addClass("show");

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

showToast('I am toasted!');
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

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

.toastDiv {
  visibility: hidden;
}

.toastDiv.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="toastDiv">
  <p class="txt_toast">blablabla</p>
</div>

Upvotes: 1

Related Questions