fade in and fade out in pure javascript without jquery

knight picture knight · Feb 22, 2015 · Viewed 11.3k times · Source

Here I have a function that fades a square box with id="box" as soon as the page loads. I tried but failed to find out how to fade in the box again or simply how to fade in a box or an element with pure JavaScript not jQuery. Here is my code for fadeOut() function:

Many thanks in advance to contributors. cheers

Answer

Anarion picture Anarion · Feb 22, 2015

I'd suggest using CSS animation

@-webkit-keyframes fadeout {
    0% {opacity:1;}
    100% {opacity:0;}
}
@keyframes fadeout {
    0% {opacity:1;}
    100% {opacity:0;}
}
.fadeOut {
  opacity:0;
  -moz-animation   : fadeout 1s linear;
  -webkit-animation: fadeout 1s linear;
  animation        : fadeout 1s linear;
}

You only need to add fadeOut class to the element