A fade-out effect gradually reduces an element’s opacity until it becomes invisible. JavaScript can create this effect by repeatedly updating the opacity property with setInterval().
- Use setInterval() to gradually reduce opacity.
- Use clearInterval() when the opacity reaches 0.
- The effect can be applied to any HTML element without external libraries.
Approach 1: Using a Separate Function
In this approach, setInterval() repeatedly calls a separate function that decreases the element's opacity until it reaches 0.
<div id="box">
<h2>GeeksforGeeks</h2>
<p>This element will fade out.</p>
</div>
<script>
let opacity = 1;
function fadeOut() {
const element = document.getElementById("box");
const intervalId = setInterval(() => {
if (opacity > 0) {
opacity -= 0.1;
element.style.opacity = opacity;
} else {
clearInterval(intervalId);
}
}, 200);
}
fadeOut();
</script>
- opacity starts at 1.
- The opacity decreases by 0.1 every 200 milliseconds.
- clearInterval() stops the animation when opacity reaches 0.
Syntax:
setInterval(functionReference, timeInterval);Approach 2: Using an Inline Function with setInterval()
Here, the fading logic is directly defined inside setInterval(), avoiding a separate function for the repeated operation.
<div id="box">
<h2>GeeksforGeeks</h2>
<p>This element will fade out.</p>
</div>
<script>
function fadeOut() {
const element = document.getElementById("box");
let opacity = 1;
const intervalId = setInterval(() => {
if (opacity > 0) {
opacity -= 0.1;
element.style.opacity = opacity;
} else {
clearInterval(intervalId);
}
}, 200);
}
fadeOut();
</script>
- The setInterval() callback runs every 200 milliseconds.
- style.opacity is updated on every iteration.
- clearInterval() stops the timer when the animation is complete.
Syntax:
const intervalId = setInterval(() => {
// animation logic
}, timeInterval);
clearInterval(intervalId);
Note: The opacity value ranges from 0 (completely transparent) to 1 (fully visible). The interval and decrement values can be adjusted to control the speed of the fade-out effect.