JavaScript: Fade a Element Using CSS Transition

, , …,
Want to master JavaScript in a week? Example based, to the point. Xah JavaScript Tutorial.

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

Code

Here's the HTML code:

<div id="id66259"><span style="font-size:500%">☯</span></div>

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

Here's the JavaScript code:

var yinyang = document.getElementById("id66259");
yinyang.style.opacity = 1;
yinyang.style.transition = "opacity 1s";

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

function fade() {
    yinyang.style.opacity = 0;
}

function unfade() {
    yinyang.style.opacity = 1;
}

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

You should first understand CSS transition, see: CSS: Transition Tutorial.

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

blog comments powered by Disqus