0

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

Community
  • 1
  • 1
Daria
  • 97
  • 3
  • 7

3 Answers3

4

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>
Banzay
  • 9,310
  • 2
  • 27
  • 46
1

Add important to your class attribute.

.load{
      opcacity: 1 !important; //because you have id selector with opacity to 0.
      }
Zakaria ASSANI
  • 276
  • 2
  • 12
1

As a good practice, try to avoid using IDs for styling.


Instead of defining the transition in the #wrapper selector, create a class containing the transition property like so:

.opacity-transition {
  transition: opacity 2s ease-in;
}

Once the transition ends, this class will not be needed any more and can be removed.

Create another class to initially hide the #wrapper element. When this class is removed it will trigger the transition.

.hidden {
  opacity: 0;
}

Code Snippet:

function fadeOnLoad() {
  //Cache the selector.
  var wrapper = document.getElementById("wrapper");
  console.log(wrapper.className);
  //Add event listener for transition end.
  wrapper.addEventListener("transitionend", function() {
    //Remove the class which is not needed anymore.
    this.classList.remove("opacity-transition");
    console.log(this.className);
  });
  //Remove hidden class to start the transition.
  wrapper.classList.remove("hidden");

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

JSFIDDLE

Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53