UNIT- IV
DOM Hierarchy: Different objects of DOM (window, navigator, history, form, frames etc.), Form
validation, Event handling in JavaScript.
Two Object Model
An object model defines the interface to the various aspects of the browser and document
that can be manipulated by JavaScript.
In JavaScript, two primary object models are employed
1. A browser object model (BOM)
The BOM provides access to the various characteristics of a browser such as the browser
window itself, the screen characteristics, and the browser history and so on.
2. Document object model (DOM).
The DOM provides access to the contents of the browser window, namely the document
including the various HTML elements ranging from anchors to images as well as any text
that may be enclosed by such elements.ls
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
What is DOM?
1. DOM stands for the Document Object Model.
2. DOM is a document content model for HTML documents.
3. It is a hierarchy of pre-existing Objects
4. A programmer can reference the object and their contents.
5. DOM stands apart from JavaScript because other scripting languages could access it.
What is its use?
DOM means the Document Object Model this is a way of describing the HTML
document to a scripting language, like JavaScript or VBScript, as objects that can
be accessed and manipulated. Objects can be added or deleted from the page and
the events triggered by these objects can be handled. Netscape and Microsoft are
both working within the W3C DOM working group,
The most important thing about objects is that you can reference them and their
contents. For instance, JavaScript allows you to reference the title of a document as
follows: document. Title
The way that document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web document. Every page has the
following objects:
Window object: Top of the hierarchy. It is the outmost element of the
object hierarchy. Hierarchy has properties that apply to the entire window.
There is also a window object for each "child window" in a frames
document.
Document object: Each HTML document that gets loaded into a window
becomes a document object. The document contains the content of the page
properties based on the content of the document, such as title, background
color, links, and forms.
Form object: Everything enclosed in the <form>...</form> tags sets the
form object.
Form control elements: The form object contains all the elements defined
for that object such as text fields, buttons, radio buttons, and checkboxes.
Navigator: has properties for the name and version of the Navigator being
used, for the MIME (Multi-Purpose Internet Mail Extensions))types
supported by the client, and for the plug-ins installed on the client.
Location: has properties based on the current URL.
History: contains properties representing URLs the client has previously
requested.
Here is a simple hierarchy of few important objects:
There are several DOMs in existence. The following sections explain each of these DOMs in
detail and describe how you can use them to access and modify document content.
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
Depending on its content, the document may contain other objects. For instance, each form
(defined by a <FORM> tag) in the document will have a corresponding FORM Object.
The Document Object Model Hierarchy is illustrated in the following figure:
The DOM represents a document as a tree. The tree is made up of parent-child relationships, a
parent can have one or many children nodes.
An idea of DOM
Let’s consider the following HTML as the starting point:
1 <html>
2 <head>
3 <title>The title</title>
4 </head>
5 <body>
6 The body
7 </body>
8 </html>
The DOM will look like that:
At the top level, there is an html node, with two children: head and body, among which
only head has a child tag title. HTML tags are element nodes in DOM tree, pieces of text
become text nodes. Both of them are nodes, just the type is different. The idea of DOM is that
every node is an object. We can get a node and change its properties like this:
1 // change background of the <BODY> element, make all red
2 document.body.style.backgroundColor = 'red';
If you have run the example above, here is the code to reset the style to default:
1 // revert background of <BODY> to default, put it back
2 document.body.style.backgroundColor = '';
It is also possible to change the contents of nodes, search the DOM for certain nodes,
create new elements and insert them into the document on-the-fly.
But first of all we need to know what DOM looks like and what it contains.
Another document
Let’s see the DOM of a more complicated document.
01 <!DOCTYPE HTML>
02 <html>
03 <head>
04 <title>The document</title>
05 </head>
06 <body>
07 <div>Data</div>
08 <ul>
09 <li>Warning</li>
10 <li></li>
11 </ul>
12 <div>Top Secret!</div>
13 </body>
14 </html>
And here is the DOM if we represent it as a tree.
Whitespace nodes
Now let’s make the picture closer to reality and introduce whitespace text elements. Whitespace
symbols in the HTML are recognized as the text and become text nodes. These whitespace
nodes are not shown in developer tools, but they do exist.
The following picture shows text nodes containing whitespaces.
By the way, note that last li does not have a whitespace text tag inside. That’s exactly because
there is no text at all inside it.
Whitespace nodes are created from spaces between nodes. So they disappear if we elimitate the
space between tags.
The example below has no whitespace nodes at all.
<!DOCTYPE
HTML><html><head><title>Title</title></head><body></body></html>
IE<9
Versions of IE lower than 9 differ from other browsers because they do not generate tags from
whitespaces. This was corrected in IE 9 as it complies with standards.
But in older IEs, the DOM tree is different from other browsers because of this.
Other node types
DOCTYPE
Did you notice a DOCTYPE from the example above? That is not shown on the picture, but
DOCTYPE is a DOM node too, located at the topmost level to the left from HTML.
DocType is part of the HTML specification and it is an instruction to the web browser about
what version of the markup language the page is written in.
Comments
Also, a HTML comment is a DOM node too:
1 <html>
2 ...
3 <!-- comment -->
4 ...
5 </html>
The comment above is also stored in DOM tree, with comment node type and textual content. It
is important when traversing nodes as we’ll see.
.
Java Script Event Handling
The objects in a Web page are organized in a hierarchy. All objects have properties and methods.
Events are things that happen, usually user actions, that are associated with an object. The "event
handler" is a command that is used to specify actions in response to an event. An event handler
executes a segment of a code based on certain events occurring within the application, such as
onLoad, onClick. JavaScript event handers can be divided into two parts: interactive event
handlers and non-interactive event handlers. An interactive event handler is the one that depends
on the user interactivity with the form or the document. For example, onMouseOver is an
interactive event handler because it depends on the users’ action with the mouse. On the other
hand non-interactive event handler would be onLoad, because this event handler would
automatically execute JavaScript code without the user's interactivity. Some of the most common
events are:
Common HTML Events
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Events and Objects
Below are some common events and the object they are associated with
Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
onClick Button, Checkbox, Submit, Reset, Link
Example:
<FORM onSubmit="functionName()">
Here are all the event handlers available in JavaScript:
Event Handler Used In
onAbort image
onBlur select, text, text area
onChange select, text, textarea
onClick button, checkbox, radio, link, reset, submit, area
onError image
onFocus select, text, testarea
onLoad windows, image
onMouseOver link, area
onMouseOut link, area
onSelect text, textarea
onSubmit form
onUnload window
onAbort:
An onAbort event handler executes JavaScript code when the user aborts loading an image.
See Example:
<HTML>
<TITLE>Example of onAbort Event Handler</TITLE>
<HEAD>
</HEAD>
<BODY>
<H3>Example of onAbort Event Handler</H3>
<b>Stop the loading of this image and see what happens:</b><p>
<IMG SRC="reaz.gif" onAbort="alert('You stopped the loading the image!')">
</BODY>
</HTML>
Here, an alert() method is called using the onAbort event handler when the user aborts loading
the image.
onBlur:
An onBlur event handler executes JavaScript code when input focus leaves the field of a text,
textarea, or a select option. For windows, frames and framesets the event handler executes
JavaScript code when the window loses focus. In windows you need to specify the event handler
in the <BODY> attribute. For example:
<BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'">
Note: On a Windows platform, the onBlur event does not work with <FRAMESET>.
See Example:
<HTML>
<TITLE>Example of onBlur Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.data.value;
if (input<0){
alert("Please input a value that is less than 0");
}
}
</SCRIPT>
</HEAD>
<BODY>
<H3> Example of onBlur Event Handler</H3>
Try inputting a value less than zero:<br>
<form name="myform">
<input type="text" name="data" value="" size=10 onBlur="valid(this.form)">
</form>
</BODY>
</HTML>
In this example, 'data' is a text field. When a user attempts to leave the field, the onBlur event
handler calls the valid() function to confirm that 'data' has a legal value. Note that the keyword
this is used to refer to the current object.
onChange:
The onChange event handler executes JavaScript code when input focus exits the field after the
user modifies its text.
See Example:
<HTML>
<TITLE>Example of onChange Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.data.value;
alert("You have changed the value from 10 to " + input );
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to something else:<br>
<form name="myform">
<input type="text" name="data" value="10" size=10 onChange="valid(this.form)">
</form>
</BODY>
</HTML>
In this example, 'data' is a text field. When a user attempts to leave the field after a change of the
original value, the onChange event handler calls the valid() function which alerts the user about
value that has been inputted.
onClick:
In an onClick event handler, JavaScript function is called when an object in a button (regular,
radio, reset and submit) is clicked, a link is pushed, a checkbox is checked or an image map area
is selected. Except for the regular button and the area, the onClick event handler can return false
to cancel the action. For example:
<INPUT TYPE="submit" NAME="mysubmit" VALUE="Submit" onClick="return
confirm(`Are you sure you want to submit the form?')">
Note: On Windows platform, the onClick event handler does not work with reset buttons.
See Example:
<HTML>
<TITLE>Example of onClick Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.data.value;
alert("Hello " + input + " ! Welcome...");
}
</SCRIPT>
</HEAD>
<BODY>
<H3> Example of onClick Event Handler </H3>
Click on the button after inputting your name into the text box:<br>
<form name="myform">
<input type="text" name="data" value="" size=10>
<INPUT TYPE="button" VALUE="Click Here" onClick="valid(this.form)">
</form>
</BODY>
</HTML>
In this example, when the user clicks the button "Click Here", the onClick event handler calls the
function valid().
onError:
An onError event handler executes JavaScript code when an error occurs while loading a
document or an image. With onError event now you can turn off the standard JavaScript error
messages and have your own function that will trace all the errors in the script. To disable all the
standard JavaScript error messages, all you need to do is set window.onerror=null. To call a
function when an error occurs all you need to do is this: onError="myerrorfunction()".
See Example:
<HTML>
<TITLE>Example of onError event handler</TITLE>
<HEAD>
<SCRIPT Language="JavaScript">
window.onerror = ErrorSetting
var e_msg="";
var e_file="";
var e_line="";
document.form[8].value="myButton"; //This is the error
function ErrorSetting(msg, file_loc, line_no) {
e_msg=msg;
e_file=file_loc;
e_line=line_no;
return true;
}
function display() {
var error_d = "Error in file: " + e_file +
"\nline number:" + e_line +
"\nMessage:" + e_msg;
alert("Error Window:\n"+error_d);
}
</SCRIPT>
</HEAD>
<BODY>
<h3> Example of onError event handler </h3>
<form>
<input type="button" value="Show the error" onClick="display()"></form>
</body>
</HTML>
Notice that the function ErrorSetting() takes three arguments: message text, URL and Line
number of the error line. So all we did was invoke the function when an error occured and set
these values to three different variables. Finally, we displayed the values via an alert method.
Note: If you set the function ErrorSetting() to False, the standard dialog will be seen.
onFocus:
An onFocus event handler executes JavaScript code when input focus enters the field either by
tabbing in or by clicking but not selecting input from the field. For windows, frames and
framesets the event handler executes JavaScript code when the window gets focused. In windows
to specify the event handler in the <BODY> attributes. We can create function also. For
example:
<BODY BGCOLOR="#ffffff" onFocus="document.bgcolor='#000000'">
Note: On a Windows platform, the onFocus event handler does not work with <FRAMESET>.
See Example:
<HTML>
<TITLE>Example of onFocus Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3>Example of onFocus Event Handler</H3>
Click your mouse in the text box:<br>
<form name="myform">
<input type="text" name="data" value="" size=10 onFocus='alert("You focused the
textbox!!")'>
</form>
</BODY>
</HTML>
In the above example, when you put your mouse on the text box, an alert() message displays a
message.
onLoad:
An onLoad event occurs when a window or image finishes loading. For windows, this event
handler is specified in the BODY attribute of the window. In an image, the event handler will
execute handler text when the image is loaded. For example:
<IMG NAME="myimage" SRC="http://rhoque.com/ad_rh.jpg" onLoad="alert('You loaded
myimage')">
See Example:
<HTML>
<TITLE>Example of onLoad Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUGE="JavaScript">
function hello(){
alert("Hello there...\nThis is an example of onLoad.");
}
</SCRIPT>
</HEAD>
<BODY onLoad="hello()">
<H3>Example of onLoad Event Handler</H3>
</BODY>
</HTML>
The example shows how the function hello() is called by using the onLoad event handler.
onMouseOver:
JavaScript code is called when the mouse is placed over a specific link or an object or area from
outside that object or area. For area object the event handler is specified with the <AREA> tag.
For example:
<MAP NAME="mymap">
<AREA NAME="FirstArea" COORDS="0,0,49,25" HREF="mylink.html"
onMouseOver="self.status='This will take you to mylink.html'; return true">
</MAP>
See Example:
<HTML>
<TITLE>Example of onMouseOver Event Handler</TITLE>
<HEAD>
</HEAD>
<BODY>
<H3> Example of onMouseOver Event Handler </H3>
<Input type = “Submit” onMouseOver = ‘alert (“Mouse is Over”)’>
</BODY>
</HTML>
onMouseOut:
JavaScript code is called when the mouse leaves a specific link or an object or area from outside
that object or area. For area object the event handler is specified with the <AREA> tag.
See Example:
<HTML>
<TITLE> Example of onMouseOut Event Handler </TITLE>
<HEAD>
</HEAD>
<BODY>
<H3> Example of onMouseOut Event Handler </H3>
Put your mouse over <A HREF="" onMouseOut="window.status='You left the link!' ; return
true;"> here</a> and then take the mouse pointer away.
</BODY>
</HTML>
In the above example, after pointing your mouse and leaving the link , the text "You left the
link!" appears on your window's staus bar.
onReset:
A onReset event handler executes JavaScript code when the user resets a form by clicking on the
reset button.
See Example:
<HTML>
<TITLE>Example of onReset Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3> Example of onReset Event Handler </H3>
Please type something in the text box and press the reset button:<br>
<form name="myform" onReset="alert('This will reset the form!')">
<input type="text" name="data" value="" size="20">
<input type="reset" Value="Reset Form" name="myreset">
</form>
</BODY>
</HTML>
In the above example, when you push the button, "Reset Form" after typing something, the alert
method displays the message, "This will reset the form!"
onSelect:
A onSelect event handler executes JavaScript code when the user selects some of the text within
a text or textarea field.
See Example:
<HTML>
<TITLE>Example of onSelect Event Handler</TITLE>
<HEAD></HEAD>
<BODY>
<H3>Example of onSelect Event Handler</H3>
Select the text from the text box:<br>
<form name="myform">
<input type="text" name="data" value="Select This" size=20 onSelect="alert('This is an
example of onSelect!!')">
</form>
</BODY>
</HTML>
In the above example, when you try to select the text or part of the text, the alert method displays
the message, "This is an example of onSelect!!".
onSubmit:
An onSubmit event handler calls JavaScript code when the form is submitted.
See Example:
<HTML>
<TITLE> Example of onSubmit Event Handler </TITLE>
<HEAD>
</HEAD>
<BODY>
<H3>Example of onSubmit Event Handler </H3>
Type your name and press the button<br>
<form name="myform" onSubmit="alert('Thank you ' + myform.data.value +'!')">
<input type="text" name="data">
<input type="submit" name ="submit" value="Submit this form">
</form>
</BODY>
In this example, the onSubmit event handler calls an alert() function when the button "Sumbit
this form" is pressed.
onUnload:
An onUnload event handler calls JavaScript code when a document is exited.
See Example:
<HTML>
<TITLE>Example 2.11</TITLE>
<HEAD>
<SCRIPT LANGUGE="JavaScript">
function goodbye(){
alert("Thanks for Visiting!");
}
</SCRIPT>
</HEAD>
<BODY onUnLoad="goodbye()">
<H3>Example of onUnload event handler</H3>
Look what happens when you try to leave this page...
</BODY>
</HTML>
In this example, the onUnload event handler calls the Goodbye() function as user exits a
document.
Note: You can also call JavaScript code via explicit event handler call. For example say you
have a function called myfunction(). You could call this function like this:
document.form.mybotton.onclick=myfunction
Notice that you don't need to put () after the function and also the event handler has to be
spelled out in lowercase.