Pages

Monday, October 29, 2012

Let web pages load before accessing JavaScript DOM objects

When you use JavaScript in a web page, you’ll often want it to perform some action or gather property values from web page elements, without the user having to take any action at all. Normally, this means writing code that will execute as the page loads. Typically, to execute JavaScript as the page loads, you simply place the code in the section without encapsulating it in a function, like so:

With this code, the browser would fill the result variable with the number 40 as the page loads.

However, when you want to interact with DOM page elements, you won’t be able to execute code in this fashion. For example, the following JavaScript:

would generate an error. That’s because as the browser parses the section, the section doesn't yet exist, and therefore, neither does the DOM element in question.

As a result, to execute code on DOM elements, you’ll need to create an initialization function that’s triggered after the web page loads (and the browser has created the DOM elements). You call this function from the tag’s onload attribute. The following code shows how this works:

Hello, world!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.