I want to create a html page that contains two divs. In the first div I want to insert an image. In the second div I want to insert the whole current content of a web page. The idea is to show only the image for few seconds and after that hide it and show the page content on a page load.
Here is what I have tried but it is not working.
<!DOCTYPE html>
<html>
<head>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body onload="show();">
<div id="myDiv">
<img id="myImage" src="Walk.gif" style="width:15%;">
</div>
<script type="text/javascript">
function show() {
var text = document.body.innerHTML;
var iDiv = document.createElement('div');
iDiv.id = 'content';
div.innerHTML=text;
document.getElementsByTagName('body')[0].appendChild(iDiv)
document.getElementById("myDiv").style.display="block";
setTimeout("hide()", 3000); // 3 wait, change the delay here
}
function hide() {
document.getElementById("myDiv").style.display="none";
document.getElementById("content").style.display="block";
}
</script>
</body>
</html>
2
Answers
Your current method is a little bit more complex than it needs to be.
Instead of trying to shove the page into the div after it loads, you could have in there originally, just hidden. You can do this using the
display:hidden
ordisplay:none
CSS attribute.An easy way to do this (and the way I prefer to) is using something called jQuery.
You can import it like this:
Then, you could switch the two’s states using jQuery.
Also, you don’t need to make a function for this. If the code is supposed to run on page load, you can simply put the <script> tag in, make it wait a few seconds, then call a function with the JQuery above, as it will run on page load anyway.
If you need a wait function, you can also use JQuery for that as well.
There’s a mistake in that code you shared, where you use
div
instead ofiDiv
. After that for some strange reason you also fetch the body doinggetElementsByTagName
while before you just diddocument.body
.Anyway if you meant to add code that would add something like a loading banner that will hide the page content for a few seconds, I suggest you to use
display: none
onbody
direct children instead of removing the whole branch and re-adding later… the page content may contain also things like<iframe>
or<script>
or<style>
elements… and it would too invasive.In this demo I show how to add a CSS rule that will hide the body direct children except the new
#loadingBanner
we are going to show during the splash screen, before the page content shows up again.