As this code is now, I must press twice to have the text appear and fade.
How can I press the button only once to have the "Added!" text appear and fade? I would like this to happen for every time I click the button (even if the user clicks WHILE the text is fading, it should start from fully visible to fading).
I have tried focus with CSS. I have also tried rearranging javascript code, as well as inserting a while loop in the javascript, but I must be doing something wrong.
Thanks
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>
2
Answers
You have to explicitly set the
display
property tonone
initially. Otherwise,text.style.display
will return an empty string.you need to use
animationend
event to remove your fade Out