cascading-style
cascading-style

Reputation: 628

Hide body until it finishes loading

I created this code so my page would be hidden until it finishes loading. But my code doesn't work as I expected. I expected this to hide the BODY until the OnLoad event was triggered. However, instead, it just stays hidden.

Any help would be appreciated, if there is maybe another, better method of hiding the BODY until it finishes loading, or what's wrong with this one.


Here's what I've tried so far:

function unveil() {
  var thebod = document.getElementById("testbody");
  thebod.STYLE = "display: block;"
}
<HTML>

<HEAD>
  <TITLE>HELLO</TITLE>
</HEAD>

<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
  <div align="CENTER">
    HELLO WORLD!
  </div>
</BODY>

</HTML>

Upvotes: 1

Views: 5190

Answers (4)

Scott Marcus
Scott Marcus

Reputation: 65806

The DOMContentLoaded event of the window object can do this. But, don't hide the body, hide a wrapper instead. And, when you set the style, make sure to set the style of a CSS property, not the style object itself.

window.addEventListener("DOMContentLoaded", function(){
  document.getElementById("wrapper").style.display = "block";
});
#wrapper { text-align:center; background:#e0e0e0; display:none;}
<HTML>

<HEAD>
  <TITLE>HELLO</TITLE>
</HEAD>

<BODY>
  <div id="wrapper">
    HELLO WORLD!
    
    <!-- The following is only added to create a delay in the 
         parsing of the document -->
    <script>
      for(var i = 0; i < 100000000; ++i){ var x = i / 3.14; }
    </script>  
  </div>
</BODY>

</HTML>

Upvotes: 3

Rounin
Rounin

Reputation: 29463

Your issue is here:

thebod.STYLE = "display: block;"

which should read:

thebod.style.display = 'block';

Here is the complete approach (using unobtrusive javascript):

var body = document.getElementsByTagName('body')[0];

function unveil() {
    body.style.display = 'block';
}

window.addEventListener('load', unveil, false);
body {
display: none;
}

div {
text-align: center;
}
<div>HELLO WORLD!</div>

Upvotes: 1

bastos.sergio
bastos.sergio

Reputation: 6764

<HTML>

<HEAD>
  <TITLE>HELLO</TITLE>
</HEAD>

<BODY ID="testbody" onload="testbody.style.display = '';" style="display: none;">
  <div align="CENTER">
    HELLO WORLD!
  </div>
</BODY>

</HTML>

Upvotes: 0

KevBot
KevBot

Reputation: 18898

You're not setting the elements 'style' correctly:

You can either do:

element.style.display = "block";

Or

element.setAttribute('style', "display: block");

Here is a working example:

function unveil() {
  var thebod = document.getElementById("testbody");
  thebod.style.display = "block";
}
<HTML>

<HEAD>
  <TITLE>HELLO</TITLE>
</HEAD>

<BODY ID="testbody" ONLOAD="unveil();" STYLE="display: none;">
  <div align="CENTER">
    HELLO WORLD!
  </div>
</BODY>

</HTML>

Upvotes: 2

Related Questions