Jump to content
m.s_shohan

What's the matter with head and body sector?

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>

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...