Tutorial

A Simple Page Fade-In With JavaScript

JavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

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;
}

0 Comments

Creative Commons License