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>