Reputation: 2473
I have a html file which looks like this.
<head>
<script>
document.onready
{
document.getElementById("demo").innerHTML="Works";
}
</script>
</head>
<body>
<div id="demo">
</div>
</body>
When I put the script tags at the bottom of the page, everything works fine. But when I put the script in <head></head
tag, it does not work. I guess it is not able to access elements that are below the script.
On many sites like StackOverflow, JavaScript is in head tag. How is it then able to access HTML elements that are below it?
What should I do now? Should I just move my script to the bottom or is there a way by which JavaScript can access elements below it?
Upvotes: 2
Views: 678
Reputation: 10398
Your syntax is incorrect.
document.ready= function () {
//code to run when page loaded
}
window.onload = function () {
//code to run when page AND images loaded
}
Upvotes: 0
Reputation: 56429
Where did you get document.onready
from? That would never work.
To ensure the page is loaded, you could use window.onload
;
window.onload = function () {
document.getElementById("demo").innerHTML="Works";
}
Upvotes: 2
Reputation: 14233
Try using something like this:
window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false);
Upvotes: 3