JibW
JibW

Reputation: 4562

JavaScript code place in the header

I am not clear why its not working the javascript code when I add it to the header section as follows.

We can place a javascript code within the body as follows

<html> 

 <head>
    <title> Simple Test </title>    
 </head>
 <body>
        <div id="mydiv"> This is the div content </div>

        <script type="text/javascript" >
           document.getElementById("mydiv").innerHTML=Date();         
        </script>   

 </body>
</html>

But when I place the same JavaScript code in the header section it doesn't work.

<html>
  <head>
   <title> Simple Test </title>

   <script type="text/javascript" >
      document.getElementById("mydiv").innerHTML=Date();         
   </script>    

  </head>

Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.

Upvotes: 2

Views: 14622

Answers (5)

tareq_moinul
tareq_moinul

Reputation: 109

<html>
  <head>
   <title> Simple Test </title>

   <script type="text/javascript" >
      window.onload= function (){document.getElementById("mydiv").innerHTML=Date();}
  </script>    
 </head>

I think above code will help you to solve your problem. You can try this one.

Upvotes: 5

Chamika Sandamal
Chamika Sandamal

Reputation: 24312

this is because of the page rendering order.you can access elements before it has been created. if you can, try to put all JavaScript code end of the page(before closing body tag). it will save your page load time. if you cannot put it in the bottom, put the code inside onload event.

Upvotes: 1

Nick
Nick

Reputation: 2468

It's because the page is being rendered in the order it's read. Therefore when the script in the header is evaluated the rest of the page hasn't been rendered yet (ie the myDiv element hasn't been created).

When you create an event handler in the head that works fine - the handler is set up before the rest of the page is loaded but the event can't happen until the element exists.

Upvotes: 3

Kae Verens
Kae Verens

Reputation: 4079

because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.

either use an "onload" event, or put your scripts at the bottom of the page.

Upvotes: 4

SLaks
SLaks

Reputation: 887453

When you put it in the <head>, it runs before the <body> exists.

Upvotes: 1

Related Questions