Search code examples
javascriptcssfade

Fade on load doesn't work


So I found this solution Using CSS for fade-in effect on page load And I've used Method 2 with raw JavaScript. Here's my code sample

JavaScript

var fadeOnLoad = function () {
  document.getElementById("wrapper").className += "load";
};
fadeOnLoad();

CSS

#wrapper {
  opacity: 0;
  transition: opacity 2s ease-in;
}

.load {
  opacity: 1;
}

Link to the website where it doesn't work https://skidle.github.io/projects/weather

And this text is crossed out in Google Dev tools enter image description here


Solution

  • try to define

    opacity: 1 !important;
    

    id selector has higher priority than class

    Here is a snippet with clear process logic. Element is invisible until body got loaded. As soon as event body onload fired, element gets opacity: 1;

    function fadeOnLoad() {
      document.getElementById("wrapper").className = "";
    };
    #wrapper {
      transition: opacity 2s ease-in;
    }
    
    .not_loaded {
      opacity: 0;
    }
    <body onload="fadeOnLoad()">
    <div id="wrapper" class="not_loaded">text</div>
    </body>