This article details how to use JavaScript programming to create dynamic HTML (DHTML) pages. The technique shown here illustrates the following key DHTML CSS JavaScript principles:
The generic solution given at the end shows how to create a document programmatically, and use the input control that is created within it to set the contents of a div tag, using a JavaScript function. A reasonable JavaScript programmer should be able to use this technique to create dynamic web pages and web interfaces such as JavaScript Shopping Carts.
The fist item that is required is a simple CSS element to contain the HTML that the JavaScript function will populate. This can be inserted in the main HTML document, or it can be automatically generated using a JavaScript function when the page is loaded.
This div has two important attributes:
When the appropriate JavaScript function is called, we shall populate the div element with HTML.
In the function which is designed to update the div area of the web page, there needs to be some way to reference the div. This is done through the JavaScript Document Object Model (DOM). This contains a function getElementById which can look up a CSS element with a unique id. This is coded as follows:
The reader will note that, given the object, the innerHTML property can be set to change the div content. The above needs to be contained inside a JavaScript function that is called from the main document when a button is clicked, or another action takes place.
In order to react to a click from the page, it is necessary to create a JavaScript function and attach it to the onClick handler of the relevant control. The code for this is as follows:
When the button is clicked, the click_handler is called, and the function executed. For an example of a generic handler, please see below.
The generic page layout should be something along these lines:
The handler can be made generic, so that it can be used with multiple controls:
Finally, the onLoad script generates the initial page, and all the controls - it could be made generic too and have more parameters passed to it:
One use for this technique is in building JavaScript Shopping Carts.