Jump to content

problem understanding window.onload event


HJohn

Recommended Posts

Hi, I am new to javascript. I am trying to understand why something that seems so simple is not working for me. I created a simple page to learn javascript. However, I don't understand why it is not working. I included a reference to an external javascript file on the head tag of the html but I always get was getting an undefined error. My question, is the window.onload event fired before or after the html file is loaded? If I put the reference to the javascript file just before the close body tag, commented on the html, it works.

 

<!DOCTYPE html><html> <head> <script type="text/javascript" src="testjavascript.js"></script> </head> <body> <h1> <script type="text/javascript"> document.write("Inside javascript") </script> </h1> <h1>Below here should be the test.</h1> <h1 id = "test">test</h1> <button id = "cmdAlert">Click Here For An Alert Message</button> <!--<script type="text/javascript" src="testjavascript.js"></script>--> </body></html>

 

javascript file

 

window.onload = initall();

function initall(){ button = window.document.getElementById("cmdAlert"); if (button) { button.onClick = "cmdAlert_Click()"; } else { alert("Can not access button."); } }

 

function cmdAlert_Click() { alert("This is a javascript test.");}

Link to comment
Share on other sites

When you assign an event handler you shouldn't use the parentheses because that would call the function right there and assign its return value to the onload property.

window.onload = initall;
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...