Fade a Element using JavaScript

By Xah Lee. Date: . Last updated: .

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

CHESHIRE CAT

Code

Here is the HTML code:

<div id="id10574">
<span style="font-size:2rem;font-family:serif;opacity:1">CHESHIRE CAT</span>
</div>

<button id="b1" type="button">Fade</button>
<button id="b2" type="button">UnFade</button>

Here is the JavaScript code:

//-*- coding: utf-8 -*-
// 2017-09-07

{

const cat = document.getElementById("id10574");

const fade = (() => {
    if (cat.style.opacity > 0) {
        // decrease opacity slightly

        cat.style.opacity = (cat.style.opacity - 0.1).toFixed(2);

       // cat.style.opacity -= 0.1; // 2013-05-14 Google Chrome bug. It never reaches 0. See http://stackoverflow.com/questions/16549614/google-chrome-javascript-fade-style-opacity-and-settimeout

        // call fade again in a fraction of a second
        setTimeout( fade, 90 );
    } else {
        cat.style.visibility = "hidden";
    }
});

const unfade = (() => {
    cat.style.opacity = 1;
    cat.style.visibility = "visible";
});

document.getElementById("b1").addEventListener ("click", fade , false);
document.getElementById("b2").addEventListener ("click", unfade , false);

}

The trick is to set CSS's opacity gradually to 0.

To do that, you use setTimeout() to call a fade function itself.

Using CSS Transitions

A more efficient way to implement fadeout is to use CSS's transition.

see Fade a Element Using CSS Transition

BUY ΣJS JavaScript in Depth