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-09-07

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

const button1 = document.getElementById("b1");
const button2 = document.getElementById("b2");

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

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

button1.addEventListener("click", fade , false);
button2.addEventListener("click", unfade , false);
}

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

[see CSS: Transition Tutorial]

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

Simple DOM Examples

  1. JS: Change CSS
  2. DOM: Change Element's Content
  3. DOM: Create HTML Element
  4. DOM: 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
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon