Search code examples
javascriptfadeout

Loading Page with fade out effect


I would like to insert a fade-out effect after a timeout.
I read how to insert fade-out but I can't insert it in my code.

(function() {
  if (window.addEventListener) {
    window.addEventListener("load", nascondi_loading_screen, false);
  } else {
    window.attachEvent("onload", nascondi_loading_screen);
  }
})();

function mostra_loading_screen() {
  document.getElementById("loading_screen").style.display = 'block';
}

function nascondi_loading_screen() {
  setTimeout(function() {
    document.getElementById("loading_screen").style.display = 'none';
  }, 3000);
}

mostra_loading_screen();
#loading_screen {
  z-index: 1000;
  display: none;
  position: absolute;
  left: 0px;
  top: 0px;
  height: 100%;
  width: 100%;
  background-color: white;
  color: white;
  text-align: center;
  padding-top: 100px;
  opacity: 0.5;
  opacity: 1;
  filter: alpha(opacity=50);
}
<div id="loading_screen">
  <img class="uk-position-center" src="images/loader.gif">
</div>


Solution

  • An element is either displayed or not. You cant have a transition on that. However you could fade out by animating the opacity. For that set the opacity in js:

     document.getElementById("loading_screen").style.opacity = 0 /* or 1 to fade in */;
    

    And then set a transition in css on that property:

     #loading_screen {
       transition: opacity ease 2s;
     }