Fade in - Fade out with JavaScript

I don’t know about you, but I rarely depend on JavaScript to perform certain visual animations/transitions - such as simply showing/hiding an element, or animating them in or out.

Usually I apply such a task to a CSS and then may use JS to append/remove CSS classes to trigger the effect.

###Example: Using CSS + JS

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.fade-in {
  opacity: 0;
  animation: fadeIn .5s ease-in 1 forwards;
}

.is-paused {
  animation-play-state: paused;
}
<div class='js-fade fade-in is-paused'>You look amazing!</div>
var el = document.querySelector('.js-fade');
if (el.classList.contains('is-paused')){
  el.classList.remove('is-paused');
}

See the Pen cxnmJ by Chris Buttery (@chrisbuttery) on CodePen.

So that’s something like my usual process. However, there have been times when I’ve needed JS to perform this simple task. Recently I found an issue with Chrome becoming confused about animating content in - from inside elements that have had clip-path applied.

With there being many ways to skin a cat - there’s many way to animate elements with JS. Looking around - it’s obvious that most people are using jQuery and its built in .fadeIn() and .fadeOut() methods. And for those few vanilla JS examples - they’re usually super abstracted and verbose.

I’ve written 2 small and succint functions below.

Example - Look Ma! Just Javascript!

// fade out

function fadeOut(el){
  el.style.opacity = 1;

  (function fade() {
    if ((el.style.opacity -= .1) < 0) {
      el.style.display = "none";
    } else {
      requestAnimationFrame(fade);
    }
  })();
}

// fade in

function fadeIn(el, display){
  el.style.opacity = 0;
  el.style.display = display || "block";

  (function fade() {
    var val = parseFloat(el.style.opacity);
    if (!((val += .1) > 1)) {
      el.style.opacity = val;
      requestAnimationFrame(fade);
    }
  })();
}

Which can be used like:


var el = document.querySelector('.js-fade');

fadeOut(el);
fadeIn(el);
fadeIn(el, "inline-block");

See the Pen hvDKi by Chris Buttery (@chrisbuttery) on CodePen.

Hey, This isn’t anything amazing!

I know.

I have just been interested in how other people are approaching this. For such a simple task, it doesnt seem right that there are so many verbose examples out there for accomplishing the same effect.

I’m always open for better examples, so feel free to suggest yours.

A gist of some other examples