You may apply a second class which has the animation, but dynamically.
const fadeInOutContainer = document.querySelector('#modal');
const fadeOut = () => {
fadeInOutContainer.classList.add('fade-out-container');
}
.fade-in-container {
background: black;
width: 200px;
height: 200px;
animation: fade-in 0.3s;
}
.fade-out-container {
animation: fade-out 0.3s;
}
@keyframes fade-in {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes fade-out {
0% { opacity: 1; }
100% { opacity: 0; }
}
<div class="fade-in-container" id="modal">
<!-- Content here... -->
</div>
<button onclick="fadeOut()">Fade out</button>
This is just a sample for the sake of example. The idea is there, adding a new class to the container itself.
I suppose the modal will not be displayed once the animation ends, that's why I leave this with the class on it. If this is not the case and the HTML element will be recycled for some reason, you should remove the dynamic class later.
Edit on demand
If you define an HTML Element with a class, the styles whitin that class will be applied by the time the element is just rendered.
*.html
<div class="test">Just for the sake of example</div>
*.css
.test { border: 1px solid red; }
Here, the container above will have a red border by the time the page loads (or the container displays).
Talking about animations, if we have
.test {
border: 1px solid red;
animation: anim 1s;
}
@keyframes anim {
0% { opacity: 0 }
100% { opacity: 1 }
}
The animation anim
will be triggered at the same time the styles whitin the test
class are being applied.
That is why you can't apply fade-in-container
and fade-out-container
to the container in your HTML file.
What you want is to trigger the fade-in
animation first (whenever the container is rendered), and that is why the container is defined with that class.
However, you want the fade-out
animation to trigger whenever you want, with an event. Like you said, it must trigger whenever the button X
is clicked.
So, you need to listen the click event of that button, then trigger the fade-out
animation.
When the fade-out
animation will be triggered? Whenever you apply the fade-out-container
class to the container.
So, to summerize,
in the *.html
<div class="fade-in-container id="modal">
<!-- Only the fade-in-container class -->
</div>
<button id="btn">Fade out</button>
and the script should look like something like
*.js
const container = document.querySelector('#modal');
const btn = document.querySelector('#btn');
btn.addEventListener(() => {
// By adding the class, the animation will be triggered
container.classList.add('fade-out-container');
});
Hope it clarifies a bit.