JS: Fade a Element Using CSS Transition

By Xah Lee. Date: . Last updated: .

This page shows you how to fade a HTML element using JavaScript by CSS transition.

FADE AWAY

Here's the HTML code:

<div id="fadeBox27921">
<span style="font-size:2rem">FADE AWAY</span>
</div>

<button id="buttonFade" type="button">Fade</button>
<button id="buttonUnfade" type="button">UnFade</button>

Here's the JavaScript code:

{
// 2013-07-10, 2019-09-29

const fadeBox27921 = document.getElementById("fadeBox27921");
const buttonFade = document.getElementById("buttonFade");
const buttonUnfade = document.getElementById("buttonUnfade");

fadeBox27921.style.opacity = 1;
fadeBox27921.style.transition = "opacity 1s";

const f_fade = (() => { fadeBox27921.style.opacity = 0; });

const f_unfade = (() => { fadeBox27921.style.opacity = 1; });

buttonFade.addEventListener("click", f_fade , false);
buttonUnfade.addEventListener("click", f_unfade , false);
}

This is done by simply setting CSS “transition” property, with changes on opacity.

[see CSS: Transition]

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials