Joe Slater
Joe Slater

Reputation: 2473

JavaScript in the head tag

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

Answers (3)

James Coyle
James Coyle

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

Mathew Thompson
Mathew Thompson

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

Adam Plocher
Adam Plocher

Reputation: 14233

Try using something like this:

window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false);

Upvotes: 3

Related Questions