m.s_shohan Posted October 10, 2016 Share Posted October 10, 2016 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 More sharing options...
dsonesuk Posted October 10, 2016 Share Posted October 10, 2016 (edited) 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 October 10, 2016 by dsonesuk Link to comment Share on other sites More sharing options...
m.s_shohan Posted October 10, 2016 Author Share Posted October 10, 2016 Got it!!! Thank you so much for the help. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now