JS DOM: Fade a Element Using CSS Transition
This page shows you how to fade a HTML element using JavaScript by CSS transition.
Example
FADE AWAY
Code
<div id="fadebox525"> <span style="font-size:2rem">FADE AWAY</span> </div> <button id="buttonFade" type="button">Fade</button> <button id="buttonUnfade" type="button">UnFade</button>
{ // 2013-07-10, 2025-04-23 const fadebox525 = document.getElementById("fadebox525"); const buttonFade = document.getElementById("buttonFade"); const buttonUnfade = document.getElementById("buttonUnfade"); fadebox525.style.opacity = 1; fadebox525.style.transition = "opacity 1s"; const f_fade = () => { fadebox525.style.opacity = 0; }; const f_unfade = () => { fadebox525.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.