JS: Fade a Element

By Xah Lee. Date: . Last updated: .

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



Here's the HTML code:

<div id="id10574"><span style="font-size:6em;opacity:1">CHESHIRE CAT</span></div>

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

Here's the JavaScript code:

//-*- coding: utf-8 -*-

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

function 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";

function 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 JS: Fade a Element Using CSS Transition

Simple DOM Examples

  1. JS: Change CSS
  2. JS: Change Element's Content
  3. JS: Create HTML Element
  4. JS: Remove HTML Element

  1. JS: document.write
  2. JS: Image Rollover
  3. JS: Pop-up New Window
  4. JS: Digital Clock
  5. JS: Stopwatch
  6. JS: Fade a Element
  7. JS: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JS: How to Create Tooltip
  10. JS: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Like what you read? Buy JavaScript in Depth