How to do fade-in and fade-out with JavaScript and CSS

Here is a simplified running example of Seattle Ninja's solution.

var slideSource = document.getElementById('slideSource');

document.getElementById('handle').onclick = function () {
  slideSource.classList.toggle('fade');
}
#slideSource {
  opacity: 1;
  transition: opacity 1s; 
}

#slideSource.fade {
  opacity: 0;
}
<button id="handle">Fade</button> 
<div id="slideSource">Whatever you want here - images or text</div>

why do that to yourself?

jQuery:

$("#element").fadeOut();
$("#element").fadeIn();

I think that's easier.

www.jquery.com


Here is a more efficient way of fading out an element:

function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);
}

you can do the reverse for fade in

setInterval or setTimeout should not get a string as argument

google the evils of eval to know why

And here is a more efficient way of fading in an element.

function unfade(element) {
    var op = 0.1;  // initial opacity
    element.style.display = 'block';
    var timer = setInterval(function () {
        if (op >= 1){
            clearInterval(timer);
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
}