ilyo ilyo - 1 year ago 49
CSS Question

Opacity transition on page load does not kicks in on load

I want to have a very simple loading effect with a quick opacity change on the whole body. So I use the following CSS

body {
opacity: 0;
transition: opacity 2s;
}

body.show-page {
opacity: 1;
}


and add
.show-page
on load. Here is the live code http://plnkr.co/edit/Ze5TiqkZYiM41VJZVDuB?p=preview

For some reason it does not transition. After the page is loaded the transition works if I add/remove this class, but when loading, it does not happen. Any idea why?

Answer Source

Your script will run before body has finished loading as the script is inside the body tag.

You maybe want something like this:

function fadeIn() {
    var body = document.getElementsByTagName('body')[0];
    body.className += 'show-page';
}
window.onload = fadeIn;

Updated Plunker

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download