Jump to content

DOM and window.onload


shadowayex
 Share

Recommended Posts

I have some DOM stuff in a function, and I set that function in the window.onload, but I get errors that the elements I'm trying to access are not defined. What I'm attempting to do is have a function in an external JS file that does some DOM stuff when the page gets loaded. I want all the of the JS code in the external file, if possible. When this didn't work, I tried doing the same thing within the HTML file itself, but it would only work if I set the window.onload after the elements that the DOM was to affect.The simplest form of the code I have right now is this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />	<title>JS Test</title>	<script type="text/javascript">		function foo()		{				element = document.getElementById("bar");			alert(element.className);		}		window.onload = foo();	</script></head><body>	<h1 id="bar" class="one two">Hello World</h1></body></html>

This gives me errors saying that element does not exist. But, if I move window.onload under the h1 element, it works fine. Is there a way to get the behavior I am looking for?

Link to comment
Share on other sites

The problem is this: window.onload = foo();With the () you are executing foo when that line of code is read. Remove () to call foo when the load event fires.
Oh, alright. So foo(); fires right away, and foo; does not. Is there a reason for this? Or somewhere where I can read up on why this happens? I'm not too educated in the specifics of JavaScript and I'd like to get a better understanding of the behavior of JavaScript and why it does what it does.
Link to comment
Share on other sites

Oh, alright. So foo(); fires right away, and foo; does not. Is there a reason for this? Or somewhere where I can read up on why this happens? I'm not too educated in the specifics of JavaScript and I'd like to get a better understanding of the behavior of JavaScript and why it does what it does.
here goes nothing...When you write a statement like this:
window.onload = foo();

the () cause the function to run right away, as you are experiencing.when written as

window.onload = foo;

you are merely assigning a reference to the function foo to the onload event handler of the window object, to be run at the time the event happens.DD, correct me if I'm wrong.

Edited by thescientist
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
 Share

×
×
  • Create New...