Back to the Web Developer's Journal Main Page
internet.com
side nav bar

Where HTML and JavaScript meet they become Dynamic HTML. With DHTML, JavaScript can refer to HTML elements on a Web page and change them. Here's our introduction to this crossover area, particularly the DOM or Document Object Model, which gives useful names to HTML elements and allows JavaScript to refer to them.

Javascript Articles:

HOW DID THEY DO THAT???

Find out in:
Amazing HTML



Site Map

Jobs at webdeveloper.com


Check out our Web-based
Discussion Groups:

Check out and join our email-based Mailing Lists for Web developers.


Developer Channel
FlashKit
Jobs.webdeveloper
JavaScript.com
JavaScriptSource
JustSMIL
ScriptSearch
Streaming Media World
WebDeveloper.com
WebReference
XMLFiles
WDVL
Discussion Groups Book Reviews Software Reviews Download Web Tools

JavaScript and HTML make the perfect couple.

An Introduction To DHTML

by Jon Perry

The Internet allows computers to communicate with other computers on an unparalleled scale. As long as all the computers talk the same language, they can understand each other.
May 15, 2000

Straightforward text is too dull for the mass-market of the Internet, and we need more complex and interesting structures to display an ever-increasing amount of data. So HTML was born.

HTML is a subset of SGML. SGML means Standard Generalized Mark-up Language. A mark-up language alters the presentation of the content of a document. A generalized mark-up language can deal with many different document types, and a standard generalized mark-up language deals with all these documents in a standardized way.

And as you know, HTML presents data in a browser window in a multitude of shapes, sizes and colors, and provides extra features, such as forms and hyperlinks.

But most computer programming languages have more functionality than HTML. They have a powerful range of commands, and can produce far more spectacular effects than HTML.

JavaScript is one such language, and JavaScript was written with the Internet in mind. We can add JavaScript to our web pages, so that we can calculate tax, or add features that depend on user commands.

And this is where we meet DHTML. DHTML is the merging of HTML and JavaScript. With DHTML we can alter the HTML page while it is being displayed, and provide animated content to the viewer.

DHTML has been primarily an Internet Explorer development, Netscape was slow to get started with it, and implemented a weak version of DHTML in NN4. NN6 has rectified this, and now Netscape supports the DOM Level 1, although this means some NN4 code has been rendered obsolete by NN6.

Anyway, to continue this exploration of DHTML, let us begin with a look at the DOM.

The DOM

The DOM is the Document Object Model. The BOM is the Browser Object Model. The DOM is nested inside the BOM.

This may not make any sense, so let's look at what it means.

Imagine a normal HTML document. It has a title, maybe some styles, some script, and a body. In the body, there are paragraphs, tables, hyperlinks and other assorted stuff. With DHTML we are aiming to manipulate these elements, and so we need to be able to refer to them.

Because of the complexity of the nature of the manipulations we are going to make, we need to store a lot of information about each element, and the browser uses the DOM to do this.

So, the DOM stores information about the currently loaded document. The BOM behaves very similarly, but it holds information about the user's system, the browser type, the location of the current document, the screen resolution, the history of the browser, the frame hierarchy, and other details.

This means that we have a 'breakdown' of the HTML document stored in the DOM. The clever bit is that JavaScript can access and change the DOM, and that JavaScript can change the DOM during run-time.

Programming DHTML

Programming DHTML can be an art form. We need to keep track of all our elements at all times. It becomes very important to give HTML elements names, and we need to keep track of likely scenarios users may encounter on the web page, as our DHTML web pages can be event-driven.

As well as being able to manipulate HTML, DHTML provides its own set of features that allow for various techniques to be used to further enhance a web page. We shall meet some of these later in this series.

A First DHTML Program

'Read before you write' in computer jargon, is as sensible as learning to walk before you run.

Let us see how we read this text box.

<HTML>
<HEAD>
<TITLE>Read Text Box</TITLE>
<BODY>
<INPUT TYPE="TEXT" NAME="myText" MAXLENGTH=10>
<BUTTON onclick="alert(myText.value);">Read Text Box</BUTTON>
</BODY>
</HTML>

Type something into the text box, and press the button. Your text is replicated in an alert box.

When we write the HTML, we need to give the <INPUT> element a name, in this case myText. myText is parsed into the DOM, where it gains a JavaScript reference, unsurprisingly 'myText'.

myText is like any other JavaScript object, it has properties. One of these properties is value, which contains the value of the myText element - the text entered into the HTML myText element. So again we see HTML and JavaScript talking to each other.

We don't use document.myText because we are already pointing at the document object, and document.myText would imply that document has a direct child object of document, which is incorrect.

Properties

We may wish to see a list of all the properties of myText.

<HTML>
<HEAD>
<TITLE>Text Box Properties</TITLE>
<SCRIPT>
function properties() {
msg='';
for (property in myText)
msg+=property+':'+myText[property]+' - ';
alert(msg);
}
</SCRIPT>
<BODY onload="properties();">
<INPUT TYPE="TEXT" NAME="myText" MAXLENGTH=10>
</BODY>
</HTML>

Quite a lot!

Different HTML elements have different features, for example, an anchor is the only element to have an HREF attribute, and an IMG is one of the few elements to have a SRC attribute. Some elements contain other elements, such as tables and selection boxes. And some elements have DOM references that are not immediately obvious, such as tables. But I hope to sort this out for you.

Writing To The DOM

Let us look at an example in which we display the information from a radio button group, in a text box.

<HTML>
<HEAD>
<TITLE>Reading Radio Buttons</TITLE>
<SCRIPT>
function info(r) {
myText.value=myRadio[r].value;
}
</SCRIPT>
</HEAD>
<BODY onload="info(0);">
<INPUT TYPE="RADIO" NAME="myRadio" CHECKED VALUE="Radio1" onclick="info(0);">Radio1
<BR>
<INPUT TYPE="RADIO" NAME="myRadio" VALUE="Radio2" onclick="info(1);">Radio2
<BR>
<INPUT TYPE="RADIO" NAME="myRadio" VALUE="Radio3" onclick="info(2);">Radio3
<BR>
<INPUT TYPE="TEXT" NAME="myText">
</BODY>
</HTML>

This may look complicated - but don't be put off. I have extended the basic principles of reading and writing the DOM into a more useful program.

The info() function is defined first, and this function both reads and writes the DOM. The parameter passed, r, stores the index for the radio button that was clicked. So:

myRadio[r].value

retrieves the value of the r-th radio button.

myText.value is a reference to the value of the text box. In this program we assign the value of the r-th radio button to the value of the text box, i.e. we read the radio collection from the DOM, and we write to the value of the text box in the DOM.

myText.value=myRadio[r].value;

The DOM is then re-calculated and re-displayed, and effectively the screen is updated.

The HTML is fairly straightforward, although the use of event handlers may be new to you. Event handlers make an element respond to an action. We have met this is many guises already, a hyperlink is activated by clicking it, and programmers say that we handle the onclick event. A hyperlink may change its color when we move the mouse over it, and this is detected by an onmouseover event.

There are many events, about 50 pre-defined ones, and in this program we detect two events, onload and onclick.

The onload event is connected to the body element, and this means that when the body element has fully loaded, do the action, in this case call the function info(0).

When a radio button is clicked, the computer automatically selects it. We can also attach extra event handlers to the click event, and indeed have done. Each radio button calls a corresponding info(n) function, which displays the change of selection in the text box.

Representing Other HTML Structures In The DOM

Every aspect of an HTML web page is mutable (can be changed) through the DOM. This includes tables, hyperlinks, forms, paragraphs, styles, images and everything else.

As a general rule of thumb, we can use:

object.property;

to reference objects and properties, but it is the exceptions to the rule that cause most problems. We will discuss more elements throughout these articles, but the best experience can be gained by practice.

Nested DOM References

The previous radio button example used HTML that looked at lot like a form. We could have extended the code slightly, and surrounded the form elements in a form. This has the knock-on effect of changing the way we must refer to the objects of the form, because they are no longer direct child objects of the implicit document object, but direct child object of the form, which is a direct child object of the document object.

So, if the HTML from before was:

<FORM NAME="myForm">
<INPUT TYPE="RADIO" NAME="myRadio" CHECKED VALUE="Radio1" onclick="info(0);">Radio1

…rest of HTML…

<INPUT TYPE="TEXT" NAME="myText">
</FORM>

Then the info() function would have to become:

function info(r) {
myForm.myText.value=myForm.myRadio[r].value;
}

The myRadio and myText elements are now seen by the DOM as child objects of myForm, and therefore we must make this point in our code.

Dynamic SELECT Boxes

A common request on comp.lang.javascript, my favorite newsgroup, is for dynamic select boxes, i.e. select boxes that can change their contents depending on a choice made by the user.

This program presents a radio box to determine the sex of the user, and then asks for their favorite color. As it is representing a very complex personality profiler system, the colors presented are different for each sex.

<HTML>
<HEAD>
<TITLE>Colors</TITLE>
<SCRIPT>
function change(s) {
switch (s) {
case 'm' : {
mySelect.options[0].value="Blue";
mySelect.options[1].value="Gray";
mySelect.options[2].value="Brown";
mySelect.options[3].value="Red";
break;
}
case 'f' : {
mySelect.options[0].value="Pink";
mySelect.options[1].value="Green";
mySelect.options[2].value="Yellow";
mySelect.options[3].value="Purple";
break;
}
}
optiontext();
}

function optiontext() {
mySelect.options[0].innerText=mySelect.options[0].value;
mySelect.options[1].innerText=mySelect.options[1].value;
mySelect.options[2].innerText=mySelect.options[2].value;
mySelect.options[3].innerText=mySelect.options[3].value;
}
</SCRIPT>
</HEAD>
<BODY onload="optiontext();">
<INPUT TYPE="radio" NAME="sex" VALUE="m" CHECKED onclick="change('m');">Male
<BR>
<INPUT TYPE="radio" NAME="sex" VALUE="f" onclick="change('f');">Female
<BR>
<SELECT SIZE="4" NAME="mySelect">
<OPTION VALUE="Blue" SELECTED>dummyvalue</OPTION>
<OPTION VALUE="Gray"></OPTION>
<OPTION VALUE="Brown"></OPTION>
<OPTION VALUE="Red"></OPTION>
</SELECT>
</BODY>
</HTML>

A program to test your programming skills!

Looking at the HTML first, this is normal HTML. dummyvalue is used as text for one of the options to enforce a certain width for the select box.

The radio buttions have onclick event handlers, and call a respective change() function.

When the body is completely loaded, the optiontext() function is called, which fills the options box texts using innerText.

The change() function is not as complicated as it looks, we refer to individual options of a select box using

selectobject.options[index]

In this program, the selectobject is mySelect, hence

mySelect.options[n].value

refers to the value property of each select option.

We use the switch statement to differentiate between the two possible cases, male or female.

We can affect all properties using DHTML. A nice quirk can be achieved by setting the SELECTED property in the code.

Add:

mySelect.options[1].selected=true;

to the male case, and

mySelect.options[2].selected=true;

to the female case, and try this.

Of course, to maintain system integrity, we would also need to re-position the SELECTED attribute in the HTML to the second element.

In the next article, we will look at addressing some of the other HTML elements through DHTML, and we will explore how we can truly excite our web pages with dynamic styles.



Jon Perry is a Freelance Author and Programmer from the UK.
Back to the Web Developer's Journal
Contact WDJ   •    Suits!   •    Propheads!   •    Ponytails!
Discuss   •    Subscribe   •    Search


internet.com

IT | Developer | Internet News | Small Business | Personal Technology | International | Search internet.com | Advertise | Corporate Info
Newsletters | Tech Jobs | E-mail Offers

internet.commerce
Be a Commerce Partner                                
  

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers