A Simple Page Fade-In With JavaScript

Page transition effects can get rather complicated to pull-off, but the following gives us a nice little fade-in effect with minimal complexity. The body element gets a fade class upon rendering, and that class is then removed right away when the DOM content is loaded. CSS takes care of the rest.

It adds a little visual magic ๐ŸŽฉ, and it can also detract the eye from something like a FOUT (flash of unstyled text). Itโ€™s even resilient to JavaScript issues and if the scripts donโ€™t load the fade class never gets applied and the effect is just never shown. Hereโ€™s how to implement it.

Add the fade class to the body element right right after the opening body tag with this one liner:

<script>
  document.body.className = 'fade';
</script>

Or, if your body tag already has other classes that you can to keep, you can add the class with classList.add():

<script>
  document.body.classList.add('fade');
</script>

Then, near the closing body tag, but before any large script files, remove the class with this:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.body.className = '';
  });
</script>

And again, if your body tag has other classes that should be kept, use classList.remove():

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.body.classList.remove('fade');
  });
</script>

And in your CSS, include something like the following to create a .7 second fade-in:

body {
  opacity: 1;
  transition: 0.7s opacity;
}

body.fade {
    opacity: 0;
    transition: none;
}
  Tweet It

๐Ÿ•ต Search Results

๐Ÿ”Ž Searching...

Sponsored by #native_company# โ€” Learn More
#native_title# #native_desc#
#native_cta#