| Introduction to DHTML |
|
| What is DHTML ? |
|
| DHTML stands for Dynamic HTML. |
|
| Dynamic HTML, a combination of HTML enhancements, scripting language and interface that are used to deliver animations, interactions and dynamic updating on web pages. The two major elements are the ECMAScript language and the DOM object model.ECMAScript is a derivative of JavaScript, and DOM is an interface that presents theHTML document to the programmer as an object model for ease in updating. |
|
| DHTML is not a standard defined by the World Wide Web Consortium (W3C).DHTML is a "marketing term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation browsers would support. DHTML is a combination of technologies used to create dynamic Web sites. |
|
| Staying on the cutting edge of web design is a hard but important thing to do. One of the buzzwords around the net is DHTML and DOM. No doubt you may have wondered exactly what in the world they are. DHTML, Dynamic HTML, allows you to alter the display of your page after it has loaded. |
|
| You must've seen neat DHTML effects at numerous sites on the net. And if you've ever looked at some code there, you may have given up on ever coding DHTML. However, don't give in just yet. DHTML is really fun and easy. In fact, it is merely a combination of a scripting language, CSS (Cascading Style Sheets), and HTML. |
|
| Why we need DHTML? |
|
| 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. SoHTML 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. |
|
| What you should already know? |
|
| As discussed above, DHTML is a combination of HTML 4.0, CSS and client-side scripting language, so it recommended that, before you continue you should have a basic understanding of the following: |
|
• HTML • CSS • JavaScript |
|
|
|
|
|
| Introduction to DHTML |
|
| Working with HTML DOM |
|
| The DOM is the Document Object Model. The BOM is the Browser Object Model. TheDOM 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 BOMbehaves 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. |
|
| Getting started with 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 DHTMLweb 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. |
|
| Your first DHTML program: |
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>My First DHTML[Easy DHTML@http://education.ebizel.com]</TITLE>
<META NAME="Generator" CONTENT="JNote">
<META NAME="Author" CONTENT="eBIZ.com Pvt Ltd">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<!--
<script language="javascript">
function sayHello()
{
alert('Hello : '+f1.txt1.value);
}
</script>
-->
</HEAD>
<BODY>
<form name="f1">
Enter Your Name : <INPUT TYPE="TEXT" NAME="txt1" MAXLENGTH=10>
<input type="button" onclick="javascript: alert('Hello : '+f1.txt1.value);
" style="color: #CC6666; font-size: 12pt; font-family: Georgia;
font-weight: bold; background-color: #000080; cursor:hand" value="Say Hello!"/>
</form>
</BODY>
</HTML>
|
|
| Click here to view the output of the file. |
|
| 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 txt1. txt1 is parsed into the DOM, where it gains a JavaScript reference, unsurprisingly 'txt1'. |
|
| txt1 is like any other JavaScript object, it has properties. One of these properties is value, which contains the value of the txt1 element - the text entered into the HTML txt1 element. So again we see HTML and JavaScript talking to each other. |
|
| Properties |
|
| 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. |
|
| Accessing properties of an element: |
|
<HTML>
<HEAD>
<META NAME="Generator" CONTENT="JNote">
<META NAME="Author" CONTENT="eBIZ.com Pvt Ltd">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<TITLE>Text Box Properties
[Easy DHTML@http://education.ebizel.com]</TITLE>
<SCRIPT>
function properties() {
msg='';
for (property in f1.myText)
msg+=property+':'+f1.myText[property]+'.'+'\n';
f1.t1.value=msg;
}
</SCRIPT>
<BODY>
<form name="f1">
<INPUT TYPE="TEXT" NAME="myText" MAXLENGTH=10 disabled=true />
<input type="button"
onclick="javascript:properties();" value="Click me" /><br>
<b>List of Properties:</b><br />
<textarea name="t1" rows="30" cols="50" ></textarea>
</form>
</BODY>
</HTML>
|
|
| Click here to view the output of the file. |
|
 |
|
|
|
|
|
| DHTML Collection and Styles |
|
| DOM Collections |
|
| As we know, the DOM stores the objects of a document and information relevant to these objects, and allows JavaScript to access the information and alter it. Changing the DOM changes the displayed page. |
|
| Individual named elements can be identified in the DOM structure readily. But we might have several instances of a particular element. To name all these individually is a fair effort, especially through multiple edits. |
|
| So the DOM uses collections. A collection is a grouping of all the same tag name elements in a document. Some collections are images, forms, links and rows. The images collection holds all the images in a document, the forms collection holds all the forms in a document, the links collection holds all the links in a document, and rows holds all the rows for a table. |
|
| Some collections have child members, for example forms have elements, and we can address the individual elements of a form through the elements collection of a member of the form collection. |
|
| Accessing Collections |
|
| Collections save us from having to name every HTML element. They also provide a ready interface for running through a list of elements. To see how a collection resembles the loaded document, let us look at an example of the forms collection. |
|
| The following has three forms, and each form has some elements. The elements are all named so that we may see the one-to-one relationship between the forms/elements collections and the HTML document. |
|
<HTML>
<HEAD>
<TITLE>Multiple Forms </TITLE>
<SCRIPT>
function showFormDetails() {
msg='';
msg+='<table width="50%" border="1" cellspacing="0" cellpadding="0">';
for (f=0;f<document.forms.length;f++) {
msg+=' <tr bordercolordark="#6600FF" bgcolor="#0099FF">';
msg+='<td colspan="2">Form '+f+'</td> <td colspan="2">
Form Name : '+document.forms[f].name+'</td>\n</tr>';
msg+='<tr>\n <td><b>Field </td>
<td><b>Form Field Type</td>
<td><b> Form Field Name</td>
<td><b>Form Field Value</td></tr>';
for (e=0;e<document.forms[f].elements.length;e++)
msg+='<tr><td>'+e+'</td>
<td> '+document.forms[f].elements[e].type+'</td>
<td> '+document.forms[f].elements[e].name+'</td>\n
<td>'+document.forms[f].elements[e].name.value+'</td></tr>';
}
msg+='</table>\n';
document.write(msg);
//alert(msg);
}
</SCRIPT>
<style type="text/css">
<!--
#Layer1 {
position:absolute;
width:500px;
height:307px;
z-index:1;
left: 198px;
top: 47px;
}
-->
</style>
</HEAD>
<BODY onload="" bgcolor="#6699FF">
<div id="Layer1">
<div STYLE="border-width: 2px;border-color: pink;
border-style: solid;width:60%;
padding-left: 2px;padding-right: 1px;padding-top: 1px;padding-bottom: 2px;
background-color: #3399CC">
<FORM NAME="form1"><FIELDSET>
|
|
<LEGEND>I am </legend>
<INPUT TYPE="RADIO" NAME="sex" value="Male">Male
<BR>
<INPUT TYPE="RADIO" NAME="sex" value="Female">Female
<BR></LEGEND>
</FIELDSET>
</FORM>
<FORM NAME="hobbies"><FIELDSET>
<LEGEND>My Hobbies are </legend>
<INPUT TYPE="CHECKBOX" NAME="sport">Sport
<BR>
<INPUT TYPE="CHECKBOX" NAME="travel">Travel
<BR>
<INPUT TYPE="CHECKBOX" NAME="music">Music
<BR>
<INPUT TYPE="CHECKBOX" NAME="puzzles">Puzzles
<BR></fieldset>
</form>
<DIV STYLE="border-width: 1px;border-color: blue;border-style: null;width:40%;">
<FORM name="LoginForm"><pre><FIELDSET>
<LEGEND>Login area </legend><label for="textfield">Login</LABEL>
<INPUT TYPE="text" NAME="ID">
<label for="password">Password</LABEL> <I
NPUT TYPE="password" NAME="password"></FORM></pre></fieldset>
<input type="submit" name="Submit" value="Submit"
style="background:#0099FF; color:#336633; font-weight:bolder; cursor:hand;
border:thin #FF9900 groove; width:200;"
onclick="javascript:showFormDetails();"/></DIV>
</FORM>
</div></div>
<br />
<br />
</BODY>
</HTML>
|
|
| Click here to view Output: |
|
| The showFormDetails () function runs through the forms collection and then through the elements collection for each form. Note that we must address document.forms here - forms[0] is not an object in its own right, it only exists as a descendant on the document object. |
|
| Working with Table Collection |
|
| While there is no need to highlight tables, the syntax and use of the collections for tables does need explaining. If we have a table, say, myTable, then a rows collection is created for myTable. This rows collection holds all the rows in myTable, and the <TH> (table head) and <TD> cells for each row are stored in the cells collection. |
|
<HTML>
<HEAD>
<TITLE>Tables DOM </TITLE>
<STYLE>
/*TD {text-align:left}*
</STYLE>
<SCRIPT>
function showTableDetails() {
msg='';
for (i=1;i<myTable.rows.length;i++) {
mrcl=myTable.rows[i].cells.length;
for (j=0;j<mrcl;j++)
//if (j<mrcl-1)
//msg+=':';
//else
//msg+='\n';
msg+=myTable.rows[i].cells[j].innerText+((j<mrcl-1)?':':'\n');
}
document.form.result.value=msg;
//alert(msg);
}
function hide()
{
alert ();
}
</SCRIPT>
</HEAD>
<BODY onload="javascript:hide();">
<TABLE ID="myTable" border="2">
<TR>
<TH>Name</TH>
|
|
<TH>Address</TH>
<TH>City</TH>
</TR>
<TR>
<TD>Aman Kumar Singh</TD>
<TD>D-232, Sector 17</TD>
<TD>Faridabad</TD>
</TR>
<TR>
<TD>R. Kumar</TD>
<TD>CD-66, Sector 909</TD>
<TD>Noida</TD>
</TR>
<TR>
<TD>Devesh</TD>
<TD>D-23, Sector 22</TD>
<TD>Noida</TD>
</TR>
<TR>
<TD>Rakhi Sawant</TD>
<TD>E-36, Sector-26/36</TD>
<TD>Noida</TD>
</TR>
<TR>
<TD>Rupa</TD>
<TD>F-35/25, Sector-36</TD>
<TD>Rohni</TD>
</TR>
</TABLE>
<br />
<br />
<a href="javascript:void(0);" onClick="showTableDetails();">
Click Here</a> to see the DOM output.
<br />
<FORM name="form">
<TEXTAREA NAME="result" ROWS="25
" COLS="50" disabled="disable"></TEXTAREA>
</FORM>
</BODY>
</HTML>
|
|
| Be cautious when working with Tables, because they do not have a NAME attribute - we must use the ID, although NAME and ID are often interchanged. |
|
| Click here to view the result. |
|
| Other collections |
|
| The images collection is referenced with: |
|
| document.images[imagenumber] |
|
| The links collection is referenced with: |
|
| document.links[linknumber] |
|
| The all collection is referenced with: |
|
| document.all[elementnumber] |
|
| The all collection is a good place to look for DIV, P and SPAN elements. |
|
|
|
|
|
| DHTML Collection and Styles |
|
| Dynamic Styles |
|
| As the Internet gained popularity, HTML became increasing weakened. People started demanding more and more features, and this caused the creation of DHTML. It also created CSS, or Cascading Style Sheets. |
|
| Styles allow us to separate the content of the HTML page from its presentation. DHTMLmakes very good use of styles - we can dynamically alter them in the same way we can alter attributes of HTML elements. This is a very powerful development - now we can move images around the screen, change an element's color in response to events, change the visibility of elements, and much more. |
|
| As a re-cap, styles are attached to an element through the style attribute, e.g. |
|
| <P STYLE="color:blue">eBIZ.com Pvt. Ltd. |
|
| Complete Code: |
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Dynamic Style </title>
<head>
</head>
<body>
<P STYLE="color:blue">eBIZ.com Pvt. Ltd.</P>
</body>
</html>
|
|
| Click here to view the result. |
|
| Alternatively, we can attach styles inside a style tag, e.g. |
|
| <STYLE> P {color:blue} </STYLE> ….. <P>eBIZ.com Pvt. Ltd.</P> |
|
| Complete code : |
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Dynamic Style </title>
<head>
<STYLE>
P {color:blue}
</STYLE>
</head>
<body>
<P>eBIZ.com Pvt. Ltd.</P>
</body>
</html>
|
|
| Click hereto view the result. |
|
| Dynamically Changing the Style |
|
| With the help of DHTML, we can control the behavior of style. We can dynamically change the style by using HTML DOM. This gives the web developer great flexibility to control the look and feel of the page contents as per the need. For example, suppose you want to highlight a particular paragraph by changing its font color, size etc. when user moves the mouse over this text and when mouse moves out of this paragraph, you want to restore the previous style of the text. |
|
| Changing Color |
|
| When we move the mouse over a hyperlink, it changes color. No other element does this, but we can easily add the effect to any element. Look at the example given below: |
|
<HTML>
<HEAD>
<TITLE>Dynamic Style </TITLE>
<STYLE>
P {
color:blue
}
</STYLE>
</HEAD>
<BODY>
<P onmouseover="style.color='red';" onmouseout="style.color='blue';">
This is an Example of Dynamic Style</P>
<P onmouseover="style.color='red';" onmouseout="style.color='blue';">
Move your mouse over the text, to highlight the text.</P>
</BODY>
</HTML>
|
|
| Click here to view the result. |
|
| Using attachEvent |
|
| You may be thinking that the code is over-complicated, and that it could be simplified. It can. Advanced DHTML provides extra keywords to allow for the dynamic nature ofDHTML. One of these is attachEvent, which allows us to attach an event handler to an element from within the script tag. |
|
<HTML>
<HEAD>
<TITLE>Dynamic Style</TITLE>
<STYLE>
P {color:blue}
</STYLE>
<SCRIPT>
function start() {
for (e=0;e<document.all.length;e++)
if (document.all[e].tagName=='P') {
document.all[e].attachEvent('onmouseover',toogle);
document.all[e].attachEvent('onmouseout',toogle1);
}
}
function toogle() {
event.srcElement.style.color='red';
}
function toogle1() {
event.srcElement.style.color='blue';
}
</SCRIPT>
</HEAD>
<BODY onload="start();">
<p>This is an Example of Dynamic Style</P>
<P>Move your mouse over the text, to highlight the text.</P></BODY>
</HTML>
|
|
| Click here to view the result. |
|
| One advantage with this code is that we no longer have to add the event handlers to every <P> element - the code does this for us by iterating through the all collection, and attaching the onmouseover and onmouseout event handlers to all P elements. |
|
| Changing fontSize |
|
function scred() {
with (event.srcElement.style) {
color='blue';
fontSize=16;
}
}
function scblack() {
with (event.srcElement.style) {
color='black';
fontSize=12;
}
}
|
|
| notice that the CSS style is font-size, whereas in script we use fontSize. All hyphenated styles folow the same pattern - remove the hyphen and capitalize the first letter of all words after the first. |
|
| So, background-color becomes backgroundColor and so on. |
|
| If you are wondering what event.srcElement means, when the event is captured, it is captured on an element. So we have an event object created by the event, and the event object has many properties about the event. One of these is srcElement, which returns the element that fired the event. And you may think that the program wrenches the text around a bit too much. Make the following changes to fix the problem: |
|
function start() {
for (e=0;e<document.all.length;e++)
if (document.all[e].tagName=='P') {
document.all[e].attachEvent('onmouseover',toogle);
document.all[e].attachEvent('onmouseout',toogle1);
}
}
|
|
and changing the style declaration to
P { color:blue;font-size:14px;} |
|
| Complete source code: |
|
<HTML>
<HEAD>
<TITLE>Dynamic Style</TITLE>
<STYLE>
P {
color:blue;
font-size:14px
}
</STYLE>
<SCRIPT>
function start() {
for (e=0;e<document.all.length;e++)
if (document.all[e].tagName=='P')
{
document.all[e].attachEvent('onmouseover',toogle);
document.all[e].attachEvent('onmouseout',toogle1);
}
}
function toogle()
{
with (event.srcElement.style) {
color='red';
fontSize=16;
}
}
function toogle1() {
with (event.srcElement.style)
{
color='blue';
fontSize=14;
}
}
</SCRIPT>
</HEAD>
<BODY onload="start();">
<p>This is an Example of Dynamic Style</P>
<P>Move your mouse over the text, to highlight the text.</P></BODY>
</HTML>
|
|
| Click here to view the result. |
|
 |
|
| Dynamically Changing the position |
|
| There are two styles that affect the position of an element, namely top and left. These two styles hold the distance of the element from the top of the screen and from the left of the screen respectively. With DHTML and Dynamic Styles, we can change the values of these styles to move an element around. |
|
| You may have seen scrolling text displays - where large bodies of text of are scrolled in a neat container. These are created by changing the position of the text inside a DIVelement. |
|
<HTML>
<HEAD>
<TITLE>Text Scroller</TITLE>
<SCRIPT>
sp=650;
function scroll() {
if (sp<-700) sp=100;
sp--;
text.style.left=sp;
setTimeout('scroll()',10);
}
</SCRIPT>
</HEAD>
<BODY onload="scroll();">
<DIV STYLE="position:absolute;overflow:hidden;top:100;left:100;width:600;
height:100;background-color:cyan">
<SPAN ID="text" STYLE="position:relative;top:50;left:0;width:800;height:100">
Here is the text that we see scrolling on the browser screen.
This DHTML Example is brought to you by eBIZ.com.
</SPAN>
</DIV>
</BODY>
</HTML>
|
|
| The DIV element contains the overflow style, this defines the behavior of the element when its contents overflow the parent's elements boundaries. The SPAN element needs an ID, and is positioned relative to its parent DIV element. This means that the co-ordinate system places (0,0) as the top-left of the DIV element. |
|
| The text that is scrolled is placed inside the SPAN element. The scroll function decrements sp, the scroll position, and then adjust the relative position of the SPANelement accordingly. This gives the movement, and the display is kept tidy because any text outside the DIV element is not shown. The animation is performed by the setTimeout function, and the scroll is repeated by detecting sp being at the end of the text (sp=-700), and resetting it to the starting position of the text (sp=650). |
|
| Click here to view the output. |
|
| Properties of STYLE |
|
| Clearly, positioning your block of content depends upon the specified STYLE properties. We seemed to pull our example properties out of a hat -- position, width, left? Where did we get these from? Well, several documents on Web contain references to the positioning properties available for style sheets -- two worth reviewing are Microsoft's CSS Attributes Reference (under "Positioning Properties") and Netscape's Defining Positioned Blocks of HTML Content. |
|
| Below we've included a handy chart summarizing the common STYLE properties which you may want to use when using the CSS syntax to position blocks of content. |
|
| position | Specifies how the block should be positioned on the page with respect to other page elements. Possible values:
"position:absolute;" Block is positioned absolutely within the browser window, relative to <BODY> block.
"position:relative;" Block is positioned relative to its parent block, if any, or else normal flow of page.
"position:static;" Block is positioned according to standard HTML layout rules -- follows flow of document. (MSIE 4+ only; Netscape 5) |
| width | Specifies the width at which the block's contents should wrap. You may specify width in measured units (50px), as a percentage of the parent block's width (50%), or auto which wraps the block according to its parent's width.
Examples: "width:50px;" or "width:50%;" |
| height | Specifies the height of the block, measured in units (50px), percentage of the parent block's height (50%), or auto. Note that the height of the block will be forced to the minimum necessary to display its contents; however, you can make the block taller than necessary.
Examples: "height:50px;" or "height:50%;" |
| left | Specifies the offset of the left edge of the block in accordance with theposition attribute. Positive measures (5px) are offset towards the right while negative measures (-5px) are offset towards the left.
Examples: "left:5px;" or "left:-5px;" |
| top | Specified the offset from the top edge of the block in accordance with the position attribute. Positive measures (5px) are offset towards the bottom of the page while negative measures (-5px) are offset towards the top of the page.
Examples: "top:10px;" or "top:-10px;" |
| clip | Specifies a rectangular portion of the block which is visible. Typically, you use the clip property if you want to show only a portion of the block, therefore hiding a portion. Syntax:
MSIE: clip:rect(top right bottom left)
Example: "clip:rect(0px 30px 50px 0px);"
Netscape: clip:rect(left,top,right,bottom)
Example: "clip:rect(0,0,30,50);"
Notice that the syntaxes vary between browsers, both in the need to specify measurement units (MSIE) and the order of the parameters. |
| visibility | Specifies whether a block should be visibile. If not visible, the block will not appear on the page, although you can make it visible later using JavaScript. The possible values for this property again vary between browsers.
MSIE:
"visbility:inherit;" Block inherits the visibility property of its parent.
"visibility:visible;" Block is visible.
"visibility:hidden;" Block is invisible.
Netscape:
"visbility:inherit;" Block inherits the visibility property of its parent.
"visibility:show;" Block is visible.
"visibility:hide;" Block is invisible. |
| z-index | Specifies the "stacking order" of blocks, should they happen to overlap other positioned blocks. A block is assigned a z-index, which is any integer. When blocks overlap, that which has the greater positive z-index appears above a block with a lower z-index. Blocks with an equal z-index value are stacked according to the order in which they appear in the source code (bottom-to-top: first block defined appears on bottom, last block defined appears on top).
Example: "z-index:3;" |
| background-color | Specifies the background color for the block.
Examples: "background-color:green;" or "background-color:FF8F00;" |
| background-image | Specifies a background image for the block.
Example: "background-image:url('images/tilewood.jpg');" |
|
|
| Employing the various STYLE properties gives you powerful control over the position and look of the blocks of content on your page. Conceptually, then, when we think inDHTML we think of a page as made up of one or more blocks. Of course, this is not immediately evident to the viewer, who essentially sees a flat Web page, without realizing that several smaller blocks of content are positioned here and there to create the overall effect. |
|
| Still, the question begs: how is this dynamic? Precise, yes, but dynamic? Consider the fact that, now that the blocks have been put into place, you can -- at any time -- change their properties. Position, background, clipping region, z-index -- it's all plastic, with the help of JavaScript, and that is the reason to be excited! |
|
|
|
|
|
| DHTML Collection and Styles |
|
| Dynamic Expressions |
|
One interesting DHTML feature in IE5+ that never quite made it into the spotlight is Dynamic Properties. By their very nature, properties defined in HTML are static, non changing (ie:
"). Dynamic Properties allows you to substitute static values in HTML with a dynamic expression instead, so instead of "300", it could be "half the width of the browser window."
|
|
| It's a nifty feature that serves to drastically reduce the amount of effort required to change certain HTML property values dynamically. Can't hurt to see what that's all about! |
|
| Dynamic Properties can be defined in two ways: |
|
• Directly within the HTML as a property value of the element in question.
• Inside your script, by dynamically attaching it to the element. |
|
| Benefits of Dynamic Expressions |
|
| Dynamic properties simplify and minimize the amount of code required in a document. Authors can use dynamic properties to implement functionality formerly possible only with scripting. This frees authors from the requirement of learning script programming before they can design advanced features for their pages. |
|
| Dynamic properties are similar to a spreadsheet's implementation of a formula. In a spreadsheet, a cell's value can be a constant or a formula. A formula can include references to any number of other cells in the spreadsheet. Likewise, a dynamic property can reference other properties on the same document. |
|
| Dynamic properties enable Web authors to describe relationships between objects, properties, and variables in terms of functions, rather than specify an explicit sequence of steps to follow. Authors merely need to concentrate on functions without constantly monitoring the current state of the document. |
|
| We can simplify the previous code by 'cutting out the middle man'. At the moment, we have sp mimicking the style of the SPAN element, and we manually connect the two. |
|
| DHTML provides expressions to link the two features automatically. An expression is set as a style, and uses variables. Then, when we change the variable, the style value also changes. For example, make the following changes to the previous text scrolling code. |
|
| Replace the scroll() function with: |
|
function scroll() {
if (sp<-350) sp=100;
sp--;
document.recalc();
setTimeout('scroll()',50);
}
|
|
| Here is the text that we see scrolling on the browser screen. This DHTML example brought to you by eBIZ.com. |
|
| (the change is in the top style, and we can remove the ID). |
|
| What we have done here is connect the top style of the SPAN to the variable sp. This means that when sp changes in the code, the top style also changes. Unfortunately, JavaScript 'hogs' the code, meaning that JavaScript prefers to finish a calculation before updating the screen. This can get very annoying with graphics, as we want to see all the intermediate steps. |
|
| Using document.recalc() forces the document to update itself, and this way we can see each individual step of the animation. We are not limited to simple expressions, try expression(sp*3) and the text will scroll thrice as fast. |
|
|
|
|
|
| DHTML Browser Object Model |
|
| Window Object |
|
| The Object Model in Overview |
|
| The browser object model can be thought of as physically part of the software that forms the browser, while Dynamic HTML is (in theory at least) a universal browser-independent document definition language. |
|
| This means that all browsers which host Dynamic HTML must provide the same object model. Otherwise, it would be impossible to create pages that performed properly on different browsers. |
|
| However, the object model is, in fact, simply an interface between the Dynamic HTMLsource code in the page, and the browser software routines that create the window and fill it with the elements defined in the page. How it does this filling of the window, or rendering of the page, is unimportant. Dynamic HTML simply defines what the results should be, not how the processes should be implemented. |
|
 |
|
| The Window Object |
|
| In previous DHTML articles we concentrated on the Document Object Model. The DOMrepresents the document displayed in a browser. But there are also circumstances in which we need to access information about the browser itself. |
|
| The root element of the BOM is the window object. As the DOM is part of the BOM, technically we should reference objects by: window.document.myElement.value; but this level of description is rarely necessary. |
|
| It is important however to be able to visualize the window as an object - and as an object it contains other child objects, as well as methods. The BOM contains one instance of a window object. This represents the instance of the browser. Further browsers have their own separate and distinct window objects. |
|
| The window object can contain frames, which in turn may contain window objects. This hierarchical system can continue indefinitely, although practical considerations do eventually interfere. |
|
| The window object has several properties, but most are too complex for this article. We will meet parent and top when we look at frames, but let's start with status and defaultStatus. |
|
|
|
|
|
| DHTML Browser Object Model |
|
| Status & Default Status |
|
| As with the DOM, we can read/write various parts of the BOM. The status line at the base of a browser screen can be read or written to using the window.status property. If the status line is left unattended, the defaultStatus property is displayed. |
|
<HTML>
<HEAD>
<TITLE>Status Demo</TITLE>
</HEAD>
<BODY onload="defaultStatus='Welcome to eBiz.com Pvt Ltd';">
<P onmouseover="javascript:window.status=new Date();">
Move the mouse over here for Date</P>
</BODY>
</HTML>
|
|
| When the document is first loaded, we change the defaultStatus property to 'Date appears here'. This is the text that appears in the status line when we are not engaging the status line elsewhere. |
|
| When the mouse is over the <P> element, we change the status line to display the current date. The status line is released from the code when the onmouseout event is fired, and this reverts the status line back to the defaultStatus message. |
|
| Click Here to view the example. |
|
 |
|
|
|
|
|
| DHTML Browser Object Model |
|
| Frames |
|
| Frames proved to be a valuable extension to the HTML language, allowing multiple documents to be displayed in a single browser. With DHTML, frames become even more powerful, with the ability to read and write across frames. |
|
| This is achieved by the usual referencing of elements, but we need to ensure that we 'travel' safely from one frame to another. |
|
| If we have a frameset document: |
|
|
<HTML>
<HEAD>
<TITLE>Frames</TITLE>
</HEAD>
<FRAMESET COLS="30%,*">
<FRAME NAME="menu" SRC="MENU.php">
<FRAMESET ROWS="50%,*">
<FRAME NAME="logo" SRC="LOGO.php">
<FRAME NAME="main" SRC="MAIN.php">
</FRAMESET>
</FRAMESET>
</HTML>
|
|
| Then we have three frames, menu, logo and main. Each .htm file is very similar in structure, but watch for the subtle differences. |
|
| menu.php |
|
<HTML>
<HEAD>
<TITLE>Menu</TITLE>
</HEAD>
<BODY>
<INPUT TYPE="text" NAME="menutext">
<BUTTON onclick="top.logo.logotext.value=menutext.value;">
To Logo</BUTTON>
<BUTTON onclick="top.main.maintext.value=menutext.value;">
To Main</BUTTON>
</BODY>
</HTML>
|
|
| logo.php |
|
<HTML>
<HEAD>
<TITLE>Logo</TITLE>
</HEAD>
<BODY>
<INPUT TYPE="text" NAME="logotext">
<BUTTON onclick="top.menu.menutext.value=logotext.value;">
To Menu</BUTTON>
<BUTTON onclick="parent.main.maintext.value=logotext.value;">
To Main</BUTTON>
</BODY>
</HTML> |
|
| main.php |
|
<HTML>
<HEAD>
<TITLE>Main</TITLE>
</HEAD>
<BODY>
<INPUT TYPE="text" NAME="maintext">
<BUTTON onclick="top.menu.menutext.value=maintext.value;">
To Menu</BUTTON>
<BUTTON onclick="parent.logo.logotext.value=maintext.value;">
To Logo</BUTTON>
</BODY>
</HTML>
|
|
| STATUS.php |
|
<HTML>
<HEAD>
<TITLE>Text Scroller</TITLE>
<SCRIPT>
sp=650;
function scroll() {
if (sp<-700) sp=650;
sp--;
text.style.left=sp;
setTimeout('scroll()',10);
}
</SCRIPT>
</HEAD>
<BODY onload="scroll();" SCROLL="NO" BGCOLOR=#6699CC>
|
<DIV STYLE="position:absolute;overflow:hidden;top:0;left:0;
width:100%;height:100;background-color:#6699CC"> |
<SPAN ID="text" STYLE="position:relative;top:5;
left:0;width:705;height:20;background-color:#6699DC"> |
Here is the text that we see scrolling on the browser screen.
This DHTML Example is brought to you by eBIZ.com. |
</SPAN>
</DIV>
</BODY>
</HTML>
|
|
| Each frame can talk to any other frame. When we do this kind of manipulation, we must take care to ensure that we are using the correct navigation path. top refers to the top-most window, i.e. the window object that all the sub-windows are descended from, and then we can travel down the tree until we get to the frame we wish to be at. |
|
| parent refers to the window directly above the current window, which is useful for nested frameset manoeuvres, rather than having to travel all the way to the top of the tree and then back down again. |
|
| Click Here to view the result. |
|
|
|
|
|
| DHTML Browser Object Model |
|
| Windows Child Object |
|
| The window object also has child objects, which contain related information about the browser. Commonly-used child objects include: |
|
• Navigator
• History
• Location |
|
| The navigator object |
|
| This object holds all the information about the type of browser and system the user is using. The navigator object has read-only properties. |
|
<HTML>
<HEAD>
<TITLE>Navigator</TITLE>
<SCRIPT>
function navigatorProperties()
{
msg='';
for (p in navigator)
msg+=p+' : '+navigator[p]+'\n';
//alert(msg);
document.f1.t1.value=msg;
}
</SCRIPT>
</HEAD>
<BODY onload="javascript:navigatorProperties();">
<h1 style="color:#99CCFF;">
List of <u>'navigator'</u> properties</h1>
<hr color=blue>
<FORM name="f1">
<TEXTAREA id="t1" NAME="t1" ROWS="20" COLS="50" disabled="true">
</TEXTAREA>
</FORM>
</BODY>
</HTML>
|
| (See example.) Different systems and setups produce different results. |
|
| The history object |
|
| When you are surfing the net, you often use the back and forward buttons to go back to a page you have already visited. The history object allows us to travel forwards and backwards in script. The use of the history object is straightforward. |
|
| history.back(); |
|
| sends us back one page |
|
| history.forward(); |
|
| We can also use |
|
| history.go(n); |
|
| which sends us forward n pages (n>0), or back n pages (n<0). |
|
| The location object |
|
| The location holds detailed information about the current URL. Replace all instances of navigator with location in the navigator example to see a list of properties and their values of the location object. |
|
| Source code: |
<HTML>
<HEAD>
<TITLE>location</TITLE>
<SCRIPT>
function locationProperties()
{
msg='';
for (p in location)
msg+=p+' : '+location[p]+'\n';
//alert(msg);
document.f1.t1.value=msg;
}
</SCRIPT>
</HEAD>
<BODY onload="javascript:locationProperties();">
<h1 style="color:#99CCFF;">List of <u>'location'</u> properties</h1>
<hr color=blue>
<FORM name="f1">
<TEXTAREA id="t1" NAME="t1" ROWS="20" COLS="50" disabled="true"><
/TEXTAREA>
</FORM>
</BODY>
</HTML>
|
|
|
|
|
|
| DHTML Browser Object Model |
|
| InnerText & InnerHTML |
|
| The entire DHTML language is fairly substantial. It contains keywords for all sorts of things - dynamic event handling, text substitution, dynamic element creation, and so on. A discussion of these is beyond the scope of this tutorial, but there are a few features that we can explore. |
|
| An Example of innerHTML: |
|
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>[Smart Cursor]</TITLE>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type>
<SCRIPT>
function moveMouse() {
eX=event.clientX;
eY=event.clientY;
CC.style.left=eX+8;
CC.style.top=eY;
di='<span style="background-color:#99CCFF; width:240">Welcome to
<font color=red>eBIZ.com</font> Pvt Ltd.';
eHc='</span></B>';
diC='<br />Current Mouse Postion : ';
if (event.srcElement.id=='D') {
eH='<B>';
}
else {
eH='';
eHc='';
}
CC.innerHTML=eH+di+'hello'+diC+eX+':'+eY+eHc;
}
</SCRIPT>
<META content="MSHTML 5.00.2314.1000" name=GENERATOR>
</HEAD>
<BODY onmousemove="javascript:moveMouse();" bgcolor="#0099FF">
<DIV id=D
style="BACKGROUND-COLOR: #00CCFF; HEIGHT: 200px; LEFT: 100px;
POSITION: absolute; TOP: 100px; WIDTH: 300px">
</DIV>
<P id=CC style="POSITION: absolute"></P>
</BODY>
</HTML>
|
| Click here to view the page. |
|
| We create a DIV element that changes the cursor, and a P element that holds the cursor position. We call the script with the onmousemove event handler, which is fired every time the mouse moves. |
|
| The moveMouse() function re-positions CC to the mouse pointer. We can detect the element that fired the mousemove event with event.srcElement. We read the id of this element, and respond. |
|
| The idea is for the cool cursor to be rendered in bold if we are over the DIV. If we are over the DIV, then eH='<B>', and eHc='</B>'. When we write the to innerHTMLproperty, we either write: |
|
| <B>x:y</B> |
|
| if we are over the DIV, or just |
|
| x:y |
|
| if we are not over the DIV. |
|
| The HTML is then parsed by the document, and you can see the change that occurs. |
|
|
|
|
|
| DHTML DOM |
|
| Hierarchical Structure Of DOM |
|
| Document Object Model |
|
| The Document Object Model has been around since browsers support JavaScript. From Netscape 2 onwards, web programmers wanted to access bits of HTML and change its properties. For instance, when you write a mouseover script you want to go to a certain image on the page and change its src property. When you do this, the browser reacts by changing the image on the screen. |
|
| The function of the Document Object Model is to provide this kind of access to HTMLelements on your page. Exactly what elements you can access in which way and exactly what you can change depends on the browser. Each higher browser version gives you more freedom to reach any element you like and change anything you like. |
|
| History of DOM |
|
| There are three DOM levels: |
|
| 1. The Level 0 DOM, supported from Netscape 2 onwards by all browsers. This DOM is treated below on this page. |
|
| 2. The two Intermediate DOMs, supported by Netscape 4 and Explorer 4 and 5. Note that the use of these DOMs is not necessary any more; I advise you to ignore them. These DOMs are treated on the archived Intermediate DOMs page. |
|
| 3. The Level 1 DOM, or W3C DOM, supported by Mozilla and Explorer 5. ThisDOM is treated in its own section. |
|
| DOM (Document Object Model) is the way to access things on the screen. And, as we've examined, there are numerous browser-inconsistancies from accessing layers with document.layers to document.all to document.getElementById. |
|
| To standardize the DOM, W3C created a future more standard Document Object Model, which is in place in some current browsers, at least partly, and will be in place (it should be) in future browsers. Currently, IE 5 supports most of the features we'll review, and NS 6 should support all of them, but both can present some problems. |
|
| The Consortium's goal, of course, is to have one standard. We've discussed accessing and manipulating layers, but with the W3C DOM, you can control almost every element on the page, create elements out of thin air, never use document.write() again, alter a page instantaneously, and much more. |
|
| Hierarchical Structure |
|
| The key to the DOM is its hierarchical structure and "family tree-like" structure. "document" refers to the actual page and content for that page; it is the "top of the tree," and everything else is underneath it. |
|
| For example, the <HTML> tag is under the document and the <HEAD> tag is under the <HTML> tag; which as we said before, is under the document; etc.... |
|
| To try to understand DOM and what it is, I'm going to use an example of a family tree. The top would be our parents and the next branch is a different person, etc.... In a realHTML document, the top would be our document, and the "branches" of the DOM "tree" are called "nodes." |
|
| Every element in a page are nodes. Examples might include <li>, <p>, and <td> tags, as well as text. In fact, every attribute, such as align="center", is (to some extent) a node. Even the value of an attribute (such as "center") is a node (a text node). |
|
 |
|
| As you might guess, browser incompatibility is the cause of all the trouble for the different ways to access a layer. When NN 4 (Netscape Navigator 4) was introduced, it was the first "DHTML browser." |
|
| Unfortunately, it was released before the W3C (World Wide Web Consortium) could issue recommended standards for the DOM. IE 4 (Microsoft Internet Explorer 4) uses a more advanced DOM in which every HTML element is programmable; however, it's nowhere near perfect. |
|
| With the related issuance of W3C standards and the introduction of IE 5 and NN 6,DHTML is now much more powerful and standard. Authors who want their pages to be available for all viewers are left to clean up after the war. |
|
| Let's look at an example. At first, we'll be working with absolutely positioned layers; later on, we'll have a go at relative positioning. |
|
| <div id="myLayer1" style="position:absolute;top:100;left:150;z-index:3"></div> |
|
| How would each browser access this object? Let's start with the "senior" model and work our way along historically. Note that layerID stands for the ID assigned to that particular layer. In our example layer, the layerID would be "myLayer1". |
|
| Netscape 4+ |
|
| In NN 4, you can access a layer with: |
|
| document.layers[i] or document.layers[layerID] or document.layers.layerID or document.layerID |
|
| We'll focus on document.layers[layerID] in this tutorial. To access our example layer, the code would be: document.layers["myLayer1"]. |
|
| Internet Explorer 4+ |
|
| With IE 4, you use: |
|
| document.all[layerID] or document.all(layerID) or document.all.layerID or layerID |
|
| We'll concentrate on the first method, but use whichever you want when you get scripting. To access our example layer, the code would be: |
|
| document.all["myLayer1"]. |
|
| W3C DOM (Internet Explorer 5 and Netscape 6) |
|
| Finally, there's the W3C DOM recommendation utilized by IE 5 and NN 6: |
|
document.getElementById(layerID)
Thus: document.getElementById("myLayer1") |
|
| We can use these same methods for the neat trick of detecting which browser a viewer is using. Consider the following code: |
|
if(document.getElementById){
// Netscape 6 and IE 5 code goes here
}else if(document.all){
// IE 4 code goes here
}else if(document.layers){
//Netscape 4 code goes here
}
|
|
| Backward compatible? |
|
| It's a good time to note here that IE 5 is backward-compatible, meaning that it can use both document.getElementById and document.all to access a page's elements. So, if you said: |
|
if(document.all){
// would return IE 4 and IE 5 } |
|
| But because of our if-else() structure in our previous example to detect browsers, that won't happen, and Internet Explorer 5 users will only return true on the first if() statement. |
|
| This is also a good time to note that Netscape 6 is not backward compatible, so you can't use document.layers to access an element in it |
|
|
|
|
|
| DHTML DOM |
|
| Accessing Elements through DOM |
|
| We can access an element (e.g., a layer) by it's ID withdocument.getElementById(ID). We can also access element nodes with document.getElementsByTagName(tagName). That returns an array of elements with that tagName. |
|
| Example: document.getElementsByTagName("TD").item(0) |
|
In the example, we grab the first table cell (<td> tag) in the document. To get an array of all tags in the document, we can use:
|
|
document.getElementsByTagName("*")
|
|
| So, to access the <body> tag, we can use: |
|
| document.getElementsByTagName("BODY").item(0) |
|
| Before applying the information provided in the past two sections, it's important to recognize two caveats. |
|
| 1. You cannot realistically reference document nodes by anything other than the id attribute in HTML (XML is OK). IE5 and NS6 both insert spurious text nodes between the ones you have written (NS6 more than IE5). |
|
| 2. <p> elements cannot be stacked according to the HTML 4.01 specification. As stated by the W3C, "The P element represents a paragraph. It cannot contain block-level elements (including P itself)." |
|
| What he means is that it's really unrealistic to access an element by using it's relation to another one (with parentNode, firstChild, previousSibling, etc...). And lastly, he is saying that <p> elements should not be contained within another <p> element. |
|
| An example |
|
| Let's look at an example of referencing each element in different ways. |
|
| Consider this page: |
|
<body>
<ol id="ol1">
<li id="li1">
<span id="span1">This is Line 1 </span>
</li>
<li id="li2">
<span id="span2">This is Line 2</span>
</li>
<li id="li3">
<span id="span3"> This is Line 3 </span>
</li>
</ol>
</body>
|
|
| Now, we can access the ol1 tag by a number of ways (remember, these may be |
|
| ineffective because of "spurious text nodes"): |
|
• document.getElementById("ol1")
• document.getElementsById("li1").parentNode
• document.getElementsByTagName("ol").item(0)
• document.getElementsByTagName("li").item(0).parentNode
• document.getElementsByTagName("li").item(1).parentNode
• document.getElementsByTagName("l1").item(2).parentNode
• document.getElementsByTagName("span").item(2).parentNode.parentNode
• document.getElementsByTagName("body").item(0).childNodes.item(0)
• document.body.childNodes.item(0) |
|
| Because we'll probably access the <body> tag a lot, we can use a shortcut (rather than using it's tagName like this: document.getElementsByTagName("BODY").item(0) or by assigning it an ID and using that): |
|
| document.body as used above. |
|
| To access l2, we could use: |
|
• document.getElementById("l2")
• document.getElementById("l1").nextSibling
• document.getElementById("l3").previousSibling
• document.getElementsByTagName("li").item(1)
• document.getElementsByTagName("span").item(1).parentNode
• document.getElementsByTagName("span").item(2).parentNode.previous Sibling
•document.getELementsByTagName("ol").childNodes.item(1).parentNode.
childNodes.item(1).parentNode.childNodes.item(1) document.getElementsByTagName("body").item(0).firstChild.firstChild.nextSibling
• document.body.childNodes.item(0).lastChild.previousSibling |
|
| Try to find the text node containing the following text--"This is Text 3." |
|
| We could find it by first accessing span3, and then accessing it's firstChild. Example: |
|
| document.getElementById("span3").firstChild |
|
| Before, I said attributes were somewhat nodes. This is why they don't show up when you try to access an element's child nodes. Later, we'll look at how to change, set, and remove attributes; but before that, let's move on to some other essentials we can access from an element node. |
|
| Level 0 DOM |
|
| The Level 0 DOM was invented by Netscape at the same time JavaScript was invented and was first implemented in Netscape 2. It offers access to a few HTMLelements, most importantly forms and (later) images. |
|
| For reasons of backward compatibility the more advanced browsers, even those who support the Level 1 DOM, still also support the old, faithful Level 0 DOM. Not supporting it would mean that the most common scripts suddenly wouldn't work any more. So even though the Level 0 DOM doesn't entirely fit into the new DOM concepts, browsers will continue to support it. |
|
| For the same reason Microsoft was at first forced to copy the Netscape DOM for Explorer 3. They wanted a real competitor for Netscape and having it produce lots of error messages on every page that contained JavaScript would have been strategically unsound. |
|
| Therefore the Level 0 DOM is really unified: all browsers that support parts of it support these parts in the same way. With the later DOMs this situation changed. |
|
| Intermediate DOMs |
|
| When the Version 4 browsers were released, the hype of the day was DHTML so both browsers had to support it. DHTML needs access to layers, separate parts of a page that can be moved across the page. Not surprisingly in view of their increasing competition, Netscape and Microsoft chose to create their own, proprietary DOMs to provide access to layers and to change their properties (their position on the page, for instance). |
|
| Netscape created the layer model and the DOM document.layers, while Microsoft used document.all. Thus a proper cross-browser DHTML script needs both intermediateDOMs. |
|
| Fortunately, nowadays these intermediate DOMs are not important any more. You can safely forget them. |
|
| Level 1 DOM |
|
| Meanwhile W3C had developed the Level 1 DOM specification. The Document Object Model W3C proposed was at first written for XML documents, but since HTML is after all a sort of XML, it could serve for browsers too. |
|
| Besides, the Level 1 DOM is a real advance. For the first time, a DOM was not only supposed to give an exact model for the entire HTML (or XML) document, it is also possible to change the document on the fly, take out a paragraph and change the layout of a table, for instance. |
|
| Since both Netscape and Microsoft had participated in the specification of the newDOM, since both browser vendors wanted to support XML in their version 5 browser and since public pressure groups like the Web Standards Project exhorted them to behave sensibly just this once, both decided to implement the Level 1 DOM. |
|
| Of course, this doesn't mean that Mozilla and Explorer 5 are the same. Again for reasons of backward compatibility Microsoft decided to continue support of document.all so that Explorer 5 now supports two DOMs (three if you count the Level 0 DOM). |
|
| On the other hand, the core of Mozilla is being built by the open source Mozilla Project and the leaders of this project have decided to completely ditch the old document.layersDOM of Netscape 4 and have Mozilla support only the Level 1 DOM. |
|
| Accessing elements |
|
| Each DOM gives access to HTML elements in the document. It requires you, the web programmer, to invoke each HTML element by its correct name. If you have done so, you can influence the element (read out bits of information or change the content or layout of the HTML element). |
|
| For instance, if you want to influence the image with name="first" you have to invoke it by its proper name and you are granted access. The Level 0 DOM supports the following nodeLists: |
|
| document.images['first'] |
|
• document.images[], which grants access to all images on the page.
• document.forms[], which grants access to all forms on the page.
• document.forms[].elements[], which grants access to all form fields in one form, whatever their tag name. This nodeList is unique to the Level 0 DOM; the W3C DOMdoes not have a similar construct.
• document.links[], which grants access to all links (<a href>) on the page.
• document.anchors[], which grants access to all anchors (<a name>) on the page. |
|
| How to use the Level 0 DOM |
|
| When the browser concludes that an HTML document has been completely loaded, it starts making arrays for you. It creates the array document.images[] and puts all images on the page in it, it creates the array document.forms[] and puts all forms on the page in it etc. |
|
| This means that you now have access to all forms and images, you just have to go through the array in search of the exact image or form that you want to influence. This can be done in two ways: by name or by number. |
|
| Suppose you have this HTML document: |
|
-------------------------------------------
| document |
| -------- ------------------- |
| |img | | second image | |
| -------- | | |
| ------------------- |
| ------------------------------------- |
| | form | |
| | --------------------- | |
| | | address | | |
| | --------------------- | |
| ------------------------------------- |
-------------------------------------------
|
|
| document.images |
|
| The first image has name="thefirst", the second has name="thesecond". Then the first image can be accessed by either of these two calls: |
|
document.images['thefirst']
document.images[0] |
|
| The second one can be accessed by either of these calls: |
|
document.images['thesecond']
document.images[1] |
|
| The first call is by name, simply fill in the name (between quotes, it's a string!) within the [] and you're ready. |
|
| The second call is by number. Each image gets a number in the document.images array, in order of appearance in the source code. So the first image on a page is document.images[0], the second one is document.images[1] etc. |
|
| document.forms |
|
| The same goes for forms. Suppose the form on the page has name="contactform", then you can reach it by these two calls: |
|
document.forms['contactform']
document.forms[0] |
|
| But in the case of forms, usually you don't want to access just the form, but a specific form field. No problem, for each form the browser automatically creates the array document.forms[].elements[] that contains all elements in the form. |
|
| The form above holds as first element an <input name="address">. You can access it by these four calls: |
|
document.forms['contactform'].elements['address'] document.forms['contactform'].elements[0]
document.forms[0].elements['address']
document.forms[0].elements[0] |
|
| These four calls are completely interchangeable, it's allowed to first use one, then another. It depends on your script exactly which method of access you use. |
|
| Doing what you need to do |
|
| Once you have correctly accessed a form field or an image through the Level 0 DOM, you'll have to do what you want to do. Images are usually accessed to create a mouseover effect that changes the property src of an image: |
|
| document.images['thefirst'].src = 'another_image.gif'; |
|
| Usually you want to access forms to check what a user has filled in. For instance to read out what the user has filled in check the property value: |
|
| x = document.forms[0].elements[0].value; |
|
| and then check x for whatever is necessary. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
0 comments: