This lightweight JavaScript code snippet helps you to create fade in-out animation. It defines functions for two buttons, “fadeBtn” and “slidBtn” to demonstrate the fading and sliding animation. When the “fadeBtn” is clicked, the “text” element fades in or out depending on its current class. When the “slidBtn” is clicked, the “slideText” element slides down or up depending on its current class. The code uses class manipulation to add or remove classes for fade in/out or slide up/down animations.
How to Create Fade In-Out Animation in JavaScript
Create the HTML structure for fading animation as follows:
<button id="fade">Fade</button>
<h1 id="fade-text"><code>I'm Faded :D</code></h1>
<button id="slid">Slide</button>
<h1 id="slide-text"><code>I'm Sliding :D</code></h1>
Now, add the following CSS styles for Fade-In and Fade-out animations. The styles for button element are optional, you can exclude them.
.body {
text-align: center;
background: purple;
}
button {
padding: 5px;
width: 100px;
height: 50px;
margin-top: 100px;
background: transparent;
color: #B39DDB;
border: 1px solid #B39DDB;
border-radius: 5px;
transition: all 1s;
font-family: monospace;
cursor: pointer;
}
button:hover {
border: none;
background: #EDE7F6;
color: #4527A0;
}
h1 {
padding: 10px;
margin: 20px;
color: #B39DDB;
opacity: 0;
}
h1#slide-text {
position: relative;
bottom: 25px;
}
.fadeIn {
animation: fadeIn .5s ease-in 1 forwards;
}
.fadeOut {
opacity: 1;
animation: fadeOut .5s ease-out 1 forwards;
}
.slideDown {
animation: slideDown .5s ease-in 1 forwards;
}
.slideUp {
animation: slideUp 1s ease-out 1 forwards;
opacity: 1;
}
@keyframes fadeIn {
to {
opacity: 1;
}
}
@keyframes fadeOut {
to {
opacity: 0;
}
}
@keyframes slideDown {
to {
bottom: 0;
opacity: 1;
}
}
@keyframes slideUp {
to {
bottom: 50px;
opacity: 0;
}
}
Finally, use the following JavaScript function to enable fade in and out effect on click event:
var text = document.getElementById("fade-text"),
fadeBtn = document.getElementById("fade"),
slidBtn = document.getElementById("slid"),
slideText = document.getElementById("slide-text");
// FadeIn and FadeOut
fadeBtn.onclick = function () {
"use strict";
if (!text.hasAttribute("class") || text.classList.contains("fadeOut")) {
text.removeAttribute("class", "fadeOut");
text.setAttribute("class", "fadeIn");
} else if (text.classList.contains("fadeIn")) {
text.classList.remove("fadeIn");
text.classList.add("fadeOut");
}
};
// SlideDown and SlideUp
slidBtn.onclick = function () {
"use strict";
if (!slideText.hasAttribute("class") || slideText.classList.contains("slideUp")) {
slideText.removeAttribute("class", "slideUp");
slideText.setAttribute("class", "slideDown");
} else if (slideText.classList.contains("slideDown")) {
slideText.classList.remove("slideDown");
slideText.classList.add("slideUp");
}
};
That’s all! hopefully, you have successfully created Fade In-Out animation in JavaScript. If you have any questions or suggestions, feel free to comment below.