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.

★ CSS TRANSITION ★

Code

Here's the HTML code:

<div id="id66259"><span style="font-size:3rem"></span></div>

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

Here's the JavaScript code:

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

{
// 2013-07-10, 2017-12-08

const star = document.getElementById("id66259");
star.style.opacity = 1;
star.style.transition = "opacity 1s";

const fade = (() => { star.style.opacity = 0; });

const unfade = (() => { star.style.opacity = 1; });

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

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

[see CSS: Transition]

For pure JavaScript version without using CSS transition, see: JS: Fade a Element.

JavaScript Fancy UI Examples

  1. JS: Image Rollover
  2. JS: Pop-up New Window
  3. JS: Digital Clock
  4. JS: Stopwatch
  5. JS: Fade a Element
  6. JS: Fade a Element Using CSS Transition
  7. JavaScript UI: Shake Element
  8. JS: How to Create Tooltip
  9. JS: Falling Snow Effect
  10. JavaScript: Floating Box Following Scroll
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

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