Jump to content

What's the matter with head and body sector?


m.s_shohan
 Share

Recommended Posts

Hi, I am learning javaScript and jQuery. In this code, I saw that if I keep the script in the head section it doesn't work.But if I keep the script in the body section it works. Can you please tell me why this happens? Thank you in advance.

<!DOCTYPE html>
<html>
<body>

<h3>Your Screen:</h3>

<div id="demo"></div>

<script>
var txt = "";
txt += "<p>Total width/height: " + screen.width + "*" + screen.height + "</p>";
txt += "<p>Available width/height: " + screen.availWidth + "*" + screen.availHeight + "</p>";
txt += "<p>Color depth: " + screen.colorDepth + "</p>";
txt += "<p>Color resolution: " + screen.pixelDepth + "</p>";

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>
Link to comment
Share on other sites

Because the JavaScript code references a element by id before the element has been rendered in the head, but after when placed below the targeted element, the element is already rendered, therefore the code will work. It can be fixed in the head by running the code after the document is fully rendered using

window.onload= function(){
var txt = "";
txt += "<p>Total width/height: " + screen.width + "*" + screen.height + "</p>";
txt += "<p>Available width/height: " + screen.availWidth + "*" + screen.availHeight + "</p>";
txt += "<p>Color depth: " + screen.colorDepth + "</p>";
txt += "<p>Color resolution: " + screen.pixelDepth + "</p>";
document.getElementById("demo").innerHTML = txt;}
Edited by dsonesuk
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...