Currently, I have to press the button twice for the text to appear and fade. How can I make it so that clicking the button once will show and fade the "Added!" text every time, even if clicked while the text is fading?
I've attempted using CSS focus, rearranging JavaScript code, and adding a while loop, but have not been successful. Any guidance would be appreciated.
function cartAdded() {
var text = document.getElementById("added-notification");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
.added-fade-out {
opacity: 0;
display: none;
animation: fadeOut 1s ease-out;
}
@keyframes fadeOut {
0% {
opacity: 1;
display: none;
}
50% {
opacity: 0.5;
display: block;
}
100% {
opacity: 0;
display: none;
}
}
<button type='button' onclick="cartAdded()">Click me</button>
<p id='added-notification' class="added-fade-out">Added!</p>
This was initially a question with unclear terminology, which led to searching for a more precise solution. The goal is to restart the animation after each click, rather than only at the end of the current animation. This aligns closely with what I am aiming to achieve (Animation should play every time you click the button)
To replay the animation after each click:
function showMessage() {
let message = document.getElementById('child');
if (message.classList.contains('d-none')) {
message.classList.remove('d-none');
}
// message.classList.add('d-none');
message.style.animation = 'none';
message.offsetHeight;
message.style.animation = null;
}
.parent {
position: relative;
width: 600px;
height: 150px;
}
@keyframes msgSuccess {
50% {
opacity: 1;
}
99% {
opacity: 0;
}
100% {
opacity: 0;
display: none;
}
}
.child {
position: absolute;
width: 100%;
height: 50px;
animation-name: msgSuccess;
animation-duration: 1s;
opacity: 0;
}
.d-none {
display: none;
}
<button onclick="showMessage()">Click Me</button>
<div id="parent" class="parent">
<div id="child" class="child d-none">Message</div>
</div>