How To Fade In and Out Using Pure CSS Javascript

INTRODUCTION

FADE MAGIC

Welcome to a tutorial on how to fade in and out using pure CSS and Javascript. So you may want to fade a section in after it is completely loaded, or maybe fade a button out once it is clicked on. In jQuery, there is a very convenient fade function. But we really don’t need to load an entire library, the fade effect can be easily done with CSS transition and Javascript:

  • First, set opacity transition on the element – <div id=”demo” style=”transition: opacity 1s”>DEMO</div>
  • Set 0 opacity to fade out – document.getElementById(“demo”).opacity = 0
  • Set 1 opacity to fade in – document.getElementById(“demo”).opacity = 1

That’s it, but just how does it work exactly? Let us walk through some examples in this guide. Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SECTION A

BASIC FADE EFFECT

All right, let us now get into an actual basic example of the fade mechanism.

 

THE CODE

1-basic.html
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Fade In And Out</title>

    <!-- (A) CSS FADE ANIMATION -->
    <style>
      .fadeani {
        transition: opacity 1s;
      }
    </style>

    <!-- (B) JS TOGGLE FADE -->
    <script>
      function fade (show) {
        if (show) {
          document.getElementById("thepara").style.opacity = 1;
        } else {
          document.getElementById("thepara").style.opacity = 0;
        }
      }
    </script>
  </head>
  <body>
    <p id="thepara" class="fadeani">
      Foo bar! Hello world! This is a dummy paragraph.
    </p>
    <input type="button" value="Fade in" onclick="fade(1)"/>
    <input type="button" value="Fade out" onclick="fade(0)"/>
  </body>
</html>

 

 

DEMO

Foo bar! Hello world! This is a dummy paragraph.

 

THE EXPLANATION

As “advertised” in the introduction above:

  • CSS animation transition: opacity 1s will actually drive the fade effect.
  • Then we simply toggle the opacity using Javascript document.getElementById("thepara").style.opacity = 0 OR 1.

 

SECTION B

COLLAPSE AFTER FADE

The above example works just fine, but you might have noticed a possible problem. The element simply fades away, but an empty space remains. Here is a small tweak to also collapse the empty space on fading.

 

THE CODE

2-collapse.html
<!DOCTYPE html>
<html>
  <head>
    <title>Fade And Collapse</title>
 
    <!-- (A) CSS OPACITY CLASSES -->
    <style>
      .fadeani {
        transition: opacity ease 1s;
      }
      .show {
        opacity: 1;
        height: auto;
      }
      .hide {
        opacity: 0;
        height: 0;
      }
    </style>
 
    <!-- (B) JS TOGGLE -->
    <script>
      function fade (show) {
        var para = document.getElementById("thepara");
        if (show) {
          para.classList.remove("hide");
          para.classList.add("show");
        } else {
          para.classList.remove("show");
          para.classList.add("hide");
        }
      }
    </script>
  </head>
  <body>
    <p id="thepara" class="fadeani">
      Foo bar! Hello world! This is a dummy paragraph.
    </p>
    <input type="button" value="Fade in" onclick="fade(1)"/>
    <input type="button" value="Fade out" onclick="fade(0)"/>
  </body>
</html>

 

 

DEMO

Foo bar! Hello world! This is a dummy paragraph.

 

EXPLANATION

You might have noticed the differences now, but the basic idea is pretty much the same:

  • We now have 2 more CSS classes:
    • .show  with opacity: 1 and height: auto.
    • .hide with opacity: 0 and height: 0.
  • As you can guess, we are simply using Javascript to toggle between these 2 classes for the fade effect now.

Some of you guys may be wondering, why don’t we just use display: none or visibility: hidden!? Sadly, as at the time of writing, CSS animation is not working with display: none – The element will simply disappear without any fade effects. Also, visibility: hidden will have the problem of retaining the empty space as above.

 

SECTION C

HARDCORE JAVASCRIPT FADE

This final method is not recommended. It is kind of here only as an “honorable mention” or “alternative solution”. This is how we do it in the old days when CSS animation is not available… Yep, you kiddos who are complaining “CSS is too difficult” just take a good look at this sh*t.

 

THE CODE

3-js-fade.html
<!DOCTYPE html>
<html>
  <head>
    <title>Hardcore JS Fade</title>
    <script>
      var fader = {
        timer : null,
        direction : null,
        cycle : null,
        animate : function () {
          let para = document.getElementById("thepara"),
              opacity = fader.cycle / 10;
          para.style.opacity = opacity;
 
          // Fade in
          if (fader.direction) { 
            fader.cycle++;
            if (fader.cycle < 11) { fader.timer = setTimeout(fader.animate, 10); }
          }
 
          // Fade out
          else {
            fader.cycle--;
            if (fader.cycle > -1) { fader.timer = setTimeout(fader.animate, 10); }
          }
        },
        go : function (show) {
          if (fader.timer != null) { clearTimeout(fader.timer); }
          fader.direction = show;
          fader.cycle = show ? 0 : 10 ; 
          fader.timer = setTimeout(fader.animate, 10);
        }
      };
    </script>
  </head>
  <body>
    <p id="thepara">
      Foo bar! Hello world! This is a dummy paragraph.
    </p>
    <input type="button" value="Fade in" onclick="fader.go(1)"/>
    <input type="button" value="Fade out" onclick="fader.go(0)"/>
  </body>
</html>

 

 

DEMO

Foo bar! Hello world! This is a dummy paragraph.

 

EXPLANATION

How this bunch of “crazy code” works is totally different from the above.

  • Instead of using CSS animations, this one uses ELEMENT.style.opacity to manually set the opacity of the element.
  • As you can see, the “animations” are driven by fader.timer = setTimeout(fader.animate, 10); It is done by repeatedly calling a timer and raising/lowering the opacity over time.

In other words, this is a “brute force” way of setting the opacity. This is not a recommended method, not just because of the complexity, but also because of how it does not use hardware acceleration. Yep, CSS animations do use hardware acceleration where possible and have better performance than this.

 

EXTRA

USEFUL BITS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

 

CHEAT SHEET

Fade Elements WIth CSS JS (click to enlarge)

 

CLOSING

WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *