JAVASCRIPT
Smooth Fade In/Out Effect for DOM Elements
Create elegant animated transitions for showing and hiding elements by gradually adjusting opacity and display properties with JavaScript.
function fadeIn(element, display = 'block') {
element.style.opacity = 0;
element.style.display = display; // Ensure element is visible for transition
let opacity = 0;
const timer = setInterval(function() {
if (opacity >= 1) {
clearInterval(timer);
}
element.style.opacity = opacity;
opacity += 0.05; // Adjust speed
}, 20); // Adjust interval for smoother or faster animation
}
function fadeOut(element) {
let opacity = 1;
const timer = setInterval(function() {
if (opacity <= 0) {
clearInterval(timer);
element.style.display = 'none'; // Hide element completely after fading
}
element.style.opacity = opacity;
opacity -= 0.05; // Adjust speed
}, 20); // Adjust interval
}
// Example Usage:
// const myElement = document.getElementById('myBox');
// document.getElementById('fadeInBtn').addEventListener('click', () => fadeIn(myElement));
// document.getElementById('fadeOutBtn').addEventListener('click', () => fadeOut(myElement));
// HTML: <div id="myBox" style="width:100px;height:100px;background:red;display:none;"></div>
// <button id="fadeInBtn">Fade In</button><button id="fadeOutBtn">Fade Out</button>
How it works: These JavaScript functions provide a simple way to animate an element's visibility. The `fadeIn` function gradually increases the element's `opacity` from 0 to 1, making it appear. The `fadeOut` function does the opposite, decreasing `opacity` from 1 to 0, then setting `display: none` to fully hide it. Both use `setInterval` to repeatedly update the opacity, creating a smooth visual effect over time.