[Solved] Fade In and Out on Button Click

[ad_1]

You only need to have the button click add the class membership, wait until the animation is complete and then remove the class.

var div = document.querySelector(".fade");
var btn = document.querySelector(".fadeButton");
btn.addEventListener("click", function(){
  div.classList.add("elementToFadeInAndOut");
  // Wait until the animation is over and then remove the class, so that
  // the next click can re-add it.
  setTimeout(function(){div.classList.remove("elementToFadeInAndOut");}, 4000);
});
.fade{
    width:200px;
    height: 200px;
    background: red;
    opacity:0;
}

.elementToFadeInAndOut {
    animation: fadeInOut 4s linear forwards;
}

@keyframes fadeInOut {
 0% { opacity:0; }
 50% { opacity:1; } 
 100% { opacity:0; } 
}
<button class="fadeButton">Button</button>
<div class="fade"></div>

1

[ad_2]

solved Fade In and Out on Button Click