Introduction

Fading content in as it comes into view is a nice effect you can add to your website to enhance your users experience. This post explains how to add that effect to your website.

The Code

JavaScript

First we'll add the following JavaScript that keeps an eye out for elements that come into view as the user scrolls vertically. We're specifically watching for elements with the class fade-in. Once those elements come into view we'll add a class of is-faded to them so we can fade them in with css.

fadeIn.js

function isInViewport(el) {
  const rect = el.getBoundingClientRect();

   // add an offset of 200 to change when the elements will fade in
  const offset = 200;

  return (
    rect.top >= 0 &&
    rect.top + offset <= (window.innerHeight || document.documentElement.clientHeight)
  );
}

function fadeIn() {
  document.querySelectorAll('.fade-in').forEach(fadeIn => {
    if (isInViewport(fadeIn)) {        
      fadeIn.classList.add('is-faded');
    }
  });
}

// run this on page load to fade in any elements already in view
fadeIn();

// run fadeIn() as user scrolls page to look for elements coming into view
document.addEventListener('scroll', function () {
  fadeIn();
}, {
    passive: true
});

CSS

We'll make sure the elements with the class fade-in start out hidden by adding opacity: 0; to them. Then once they are scrolled into view and have the class is-faded we'll fade them in using the fadeIn keyframe animation.

fade-in.css

.fade-in {
  opacity: 0;
}

.is-faded {
  animation: fadeIn 1200ms both;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(50px);
  }
  
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

Wrapping Up

Now that we have our JavaScript and CSS in place, any element that we add the fade-in class to will start out hidden and get faded in when they come into view.

Live example

https://codepen.io/zpthree/full/abVoqxY

Source code

https://codepen.io/zpthree/pen/abVoqxY