JavaScript: 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 is 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 is 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]

BUY ΣJS JavaScript in Depth