Sometimes, we want to do fade-in and fade-out with JavaScript and CSS.
In this article, we’ll look at how to do fade-in and fade-out with JavaScript and CSS.
How to do fade-in and fade-out with JavaScript and CSS?
To do fade-in and fade-out with JavaScript and CSS, we use the transition
CSS property.
For instance, we write
<button id="handle">Fade</button>
<div id="slideSource">Whatever you want here - images or text</div>
to add a button and the div we want to element.
Then we write
#slideSource {
opacity: 1;
transition: opacity 1s;
}
#slideSource.fade {
opacity: 0;
}
to add the transition effects with the transition
property.
We animate the opacity
between 0 and 1.
Then we write
const slideSource = document.getElementById("slideSource");
document.getElementById("handle").onclick = () => {
slideSource.classList.toggle("fade");
};
to select the div with getElementById
.
And then we select the button and set its onclick
property to a function that toggles the fade
class to animate the opacity between 1 and 0 and vice versa when we click on it.
Conclusion
To do fade-in and fade-out with JavaScript and CSS, we use the transition
CSS property.