JavaScript and the HTML layout

JavaScript Object Property values are based on the content of your HTML document, sometimes referred to as reflection because the property values reflect the HTML. To understand JavaScript reflection, it is important to understand how the Browser performs the layout -- the process by which the Browser transforms HTML tags into graphical display on your computer.

Generally, the layout happens sequentially in the Browser: the Browser starts at the top of the HTML file and works downward, displaying output to the screen as it goes. Because of this "top-down" behavior, JavaScript reflects only HTML that it has encountered. For example, suppose you define a form with a couple of text-input elements:

<FORM NAME="statform">
  <INPUT TYPE="text" NAME="userName" VALUE="Jon">
  <INPUT TYPE="text" NAME="Age" VALUE="32">

These form elements are reflected as JavaScript Objects that you can use after the form is defined: document.statform.userName and document.statform.Age. For example, you could display the value of these objects in a script after defining the form:

<SCRIPT>
     document.write(document.statform.userName.value);
     document.write(" you are ");
     document.write(document.statform.Age.value);
</SCRIPT>

NOTE: The Script will produce Jon you are 32.

However, if you tried to do this before the form definition (above it in the HTML page), you would get an error, because the Objects don't exist yet in the Navigator Object.

Likewise, once layout has occurred, setting a property value does not affect its value or appearance. For example, suppose you have a document title defined as follows:

<TITLE>My JavaScript Page</TITLE>

This is reflected in JavaScript as the value of document.title. Once the Navigator has displayed this in the Title Bar of the Browser window, you cannot change the value in JavaScript. If you have the following script later in the page, it will not change the value of document.title, it will not affect the appearance of the page, or generate an error.

document.title = "The New Improved JavaScript Page"

There are some important exceptions to this rule: you can update the value of Form Elements dynamically. For example, the following script defines a text field that initially displays the string "Starting Value." Each time you click the button, you add the text "...Updated!" to the value.

<FORM NAME="demoForm">
  <INPUT TYPE="text" NAME="mytext" VALUE="Starting Value"><P>
  <INPUT TYPE="button" VALUE="Update Text Field"
   
onClick="document.demoForm.mytext.value += '...Updated!'">
</FORM>

This is a simple example of updating a form element after the layout.

Using Event Handlers, you can also change a few other properties after the layout has completed, for example, document.bgColor as we have already seen.