Hello! I’m trying to implement an animation and it doesn’t seem to work as I expect it to. So, let’s consider the following code (HTML, CSS, JS in order):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test site</title>
<link rel="stylesheet" href="style.css" type="text/css" media="all">
</head>
<body>
<!-- The text will be placed inside this div. At first, this is empty -->
<div id="fade_in_out_text_here"></div>
<!-- That button will be used to update the text -->
<button>Press me!</button>
</body>
<script src="script.js"></script>
</html>
*, *::before, *::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: grid;
place-content: center;
gap: 1rem;
min-height: 100vh;
min-width: 100vw;
}
.animation_class {
font-size: 3rem;
color: red;
animation-name: fade_in_out;
animation-duration: 5s;
animation-direction: alternate;
}
@keyframes fade_in_out {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
let num = 0
const text_div = document.getElementById("fade_in_out_text_here")
const btn = document.querySelector("button")
text_div.classList.add("animation_class")
btn.onclick = () => {
text_div.innerText = `${num}`
num++
}
So, there is a `div` (empty at first) where I’ll place some text and then, there is a button that is used to update the text.. Then, there is an animation that starts with “opacity” been 0 and then ends up with “opacity” been 1. I’m assigning this animation a “direction” of `alternate` that plays the animation and then, plays it again with the opposite effect.
What I expect to happen is the press the button, fade it in and then, fade it out until it disappears again. Any ideas what I’m doing wrong?