Question Overflow
Question Overflow

Reputation: 11275

Why does positioning of <script> in HTML for window.onload event matters?

I have a form that hides a text input field dynamically, depending on the initial choice of an option field upon loading. After some trial and error, I realise that the <script> tag has to be placed below the <form> elements in order for this functionality to work:

<html>
....
 <body>
....
  <form>
   <select name=choice>
    <option value=0 selected>Default</option>
    <option value=1>Others</option>
   </select>
   <input type=text name=others></input>
  </form>
....
  <script type='text/javascript'>
   function init()
   {
    var A = document.forms[0].choice;
    var B = document.forms[0].others;
    if(A.options[A.selectedIndex].value == 0) B.style.display = 'none';
   }
   window.onload = init();
  </script>
....
 </body>
</html>

The event window.onload is a global event that is triggered after all resources of the page including DOM, images, frames, etc have loaded. Then, why is it still necessary for the <script> tag to be placed below the <form> elements?

Upvotes: 0

Views: 347

Answers (3)

user94893
user94893

Reputation:

JavaScript and HTML works correctly. But I see some miss understand on your code.

window.onload = init(); 

This line means use execute init function immediately and set function result as onload event. That is the reason why it works when you place it under form element.

Upvotes: 1

djd
djd

Reputation: 5188

It's because of a typo in your code:

window.onload = init();

This is actually calling the init function immediately (and then setting window.onload to undefined). Try:

window.onload = init;

Upvotes: 1

Alex
Alex

Reputation: 35407

Because your executing the init function instead assigning the pointer to the function...

Change:

window.onload = init();

To:

window.onload = init;

Upvotes: 5

Related Questions