UNIT-4 Java Script and HTML Documents Web Designing BCA I Sem NEP
THE JAVASCRIPT EXECUTIONENVIRONMENT
A browser displays an XHTML document in a window on the screen of the client.
The JavaScript Windowobject represents the window that displays the document.
The properties of the Window object are visible to all JavaScript scripts that appear
either implicitly or explicitly in the window’s XHTML document, so they include all of
the global variables.
Every Windowobject has a property named document, which is a reference to the
Documentobject that the window displays.
Every Document object has a forms array, each element of which represents a
form in the document.
Each forms array element has an elements array as a property, which contains
the objects that represent the XHTML form elements, such as buttons and
menus.
Documentobjects also have property arrays for anchors, links, images, and applets.
THE DOCUMENT OBJECT MODEL
The original motivation for the standard DOM was to provide a specification that
would allow Java programs and JavaScript scripts that deal with XHTML documents to
be portable among various browsers.
The DOM is an application programming interface (API) that defines an interface
between XHTML documents and application programs.
It is an abstract model because it must apply to a variety of application programming
languages.
Each language that interfaces with the DOM must define a binding to that interface.
The actual DOM specification consists of a collection of interfaces, including one for
each document tree node type.
They define the objects, methods, and properties that are associated with their
respective node types.
With the DOM, users can write code in programming languages to create
documents, move around in their structures, and change, add, or delete elements
and their content.
Documents in the DOM have a treelike structure, but there can be more than one tree
in a document.
Because the DOM is an abstract interface, it does not dictate that documents be
implemented as trees or collections of trees.
From the desk of Roopa R,S.G.T College,Bellary. Page 1
UNIT-4 Java Script and HTML Documents Web Designing BCA I Sem NEP
From the desk of Roopa R,S.G.T College,Bellary. Page 2
UNIT-4 Java Script and HTML Documents Web Designing BCA I Sem NEP
document
<head> <body>
<title> <table>
“a simple table” <tr> <tr>
<th> <td> <td> <th> <td> <td>
apple orange “breakfast” “0” “1”
A language that is designed to support the DOM must have a binding to the DOM constructs.
In the JavaScript binding to the DOM, the elements of a document are objects, with both
data and operations.
The data are called properties, and the operations are, naturally, called methods.
Example: <input type = “text” name = “address”>
From the desk of Roopa R,S.G.T College,Bellary. Page 3
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
ELEMENT ACCESS IN JAVASCRIPT
The elements of an XHTML document have corresponding objects that are visible to an embedded
JavaScript script. There are several ways the object associated with an XHTML form element can
be addressed in JavaScript. The original (DOM 0) way is to use the formsand elements arrays of the
Documentobject, which is referenced through the document property of the Window object.
Example:
The DOM address of the button in this example, using the forms and elements arrays, is as follows:
var dom = [Link][0].elements[0];
The problem with this approach to element addressing is that the DOM address is defined by address
elements that could change—namely, the forms and elements arrays.
Another Approach:
Using the name attributes, the button’s DOM address is as follows:
var dom = [Link];
One drawback of this approach is that the XHTML 1.1 standard does not allow the name attribute in
the form element, even though the attribute is now valid for form elements. This is a validation
problem, but it causes no difficulty for browsers. Hence, alternatively we use,
var dom = [Link](“turnItOn”);
Buttons in a group of checkboxes often share the same name. The buttons in a radio button group
always have the same name. In these cases, the names of the individual buttons obviously cannot be
used in their DOM addresses. To access the arrays, the DOM address of the form object must first be
obtained, as shown:
The checked property of a checkbox object is set to true if the button is checked. For t he preceding
sample checkbox group, the following code would count the number of checkboxes that were checked:
Radio buttons can be addressed and handled exactly as are the checkboxes in the foregoing code.
From the desk of Roopa R ,S.G.T College,Ballari. Page 4
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
EVENTS AND EVENT HANDLING
BASIC CONCEPTS OF EVENT HANDLING
One important use of JavaScript for Web programming is to detect certain activities of the
browser and the browser user and provide computation when those activities occur. These
computations are specified with a special form of programming called event-driven
programming.
In conventional (non-event-driven) programming, the code itself specifies the order in
which it is executed, although the order is usually affected by the program’s input data.
In event-driven programming, parts of the program are executed at completely
unpredictable times, often triggered by user interactions with the program that is
executing.
An event is a notification that something specific has occurred, either with the browser, such
as the completion of the loading of a document, or because of a browser user action, such as a
mouse click on a form button.
An event handler is a script that is implicitly executed in response to the appearance of an
event. Event handlers enable a Web document to be responsive to browser and user
activities.
One of the most common uses of event handlers is to check for simple errors and
omissions in user input to the elements of a form, either when they are changed or when
the form is submitted.
This kind of checking saves the time of sending incorrect form data to the server.
Because events are JavaScript objects, their names are case sensitive. The names of all
event objects have only lowercaseletters.
Events are created by activities associated with specific XHTML elements.
The process of connecting an event handler to an event is called registration.
There are two distinct approaches to event handler registration, one that assigns tag
attributes and one that assigns handler addresses to object properties.
EVENTS, ATTRIBUTES, AND TAGS
From the desk of Roopa R ,S.G.T College,Ballari. Page 5
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
In many cases, the same attribute can appear in several different tags. The circumstances under
which an event is created are related to a tag and an attribute, and they can be different for the
same attribute when it appears in different tags.
There are two ways to register an event handler in the DOM 0 event model. One of these is by
assigning the event handler script to an event tag attribute, as in the following example:
In many cases, the handler consists of more than a single statement. In these cases, often a function
is used and the literal string value of the attribute is the call to the function. Consider the example of
a button element:
An event handler function could also be registered by assigning its name to the associated event
property on the button object, as in the following example:
From the desk of Roopa R ,S.G.T College,Ballari. Page 6
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
HANDLING EVENTS FROM BODY ELEMENTS
The events most often created by body elements are load and unload. As our first example of
event handling, we consider the simple case of producing an alert message when the body of the
document has been loaded. In this case, we use the onload attribute of <body> to specify the event
handler:
Output:
The unload event is probably more useful than the load event. It is used to do some cleanup before a
document is unloaded, as when the browser user goes on to some new document. For example, if the
document opened a second browser window, that window could be closed by an unload event
handler.
HANDLING EVENTS FROM BUTTON ELEMENTS
Buttons in a Web document provide an effective way to collect simple input from the browser user.
Example:
//radio_click.html
<html>
<head>
<title> radio_click.html</title>
<script type = "text/javascript" src = "radio_click.js">
</script>
</head>
From the desk of Roopa R ,S.G.T College,Ballari. Page 7
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
<body>
<h4> Choose your favourite Color</h4>
<form id = "myForm" action = " radio_click.js">
<p>
<label><input type = "radio" name = "dButton" value = "1" onclick = "dChoice(1)"/> RED</label><br/>
<label><input type = "radio" name = "dButton" value = "2" onclick = "dChoice(2)"/> BLUE</label><br/>
<label><input type = "radio" name = "dButton" value = "3" onclick = "dChoice(3)"/> GREEN</label><br/>
<label><input type = "radio" name = "dButton" value = "4" onclick = "dChoice(4)"/> YELLOW</label>
</p>
</form>
</body>
</html>
//radio_click.js function dChoice(ch)
{
switch(ch)
{
case 1: alert("You have choosen RED COLOR");
break;
case 2: alert("You have choosen BLUE COLOR");
break;
case 3:alert("You have choosen GREEN COLOR");
break;
case 4: alert("You have choosen YELLOW COLOR");
break;
default:alert("Ooops..Invalid choice:Try Again");
break;
}
}
Output:
From the desk of Roopa R ,S.G.T College,Ballari. Page 8
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
The next example, radio_click2.html, whose purpose is the same as that of radio_click.html, registers
the event handler by assigning the name of the handler to the event properties of the radio button
objects.
The following example uses three files—one for the XHTML, one for the script for the event handlers,
and one for the script to register the handlers:
There are two advantages to registering handlers as properties over registering them in XHTML
attributes.
First, it is good to keep XHTML and Java-Script separated in the document. This allows a kind
of modularization of XHTML documents, resulting in a cleaner design that will be easier to
maintain.
Second, having the handler function registered as the value of a property allows for the
possibility of changing the function duringuse.
HANDLING EVENTS FROM TEXT BOX AND PASSWORD ELEMENTS
Text boxes and passwords can create four different events: blur, focus, change, and select.
// [Link]
<html>
<head><title>[Link]</title>
<script type = "text/javascript" src = "[Link]">
</script>
</head>
<body>
<form action = " ">
<h3> Items Order Form</h3>
<table border="border">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<th>TV</th>
<td>Rs.25000</td>
<td><input type = "text" id = "tv" size = "2"/>
</td> After Click Total Cost Button, we get
</tr>
<tr>
<th>Refrigerator</th>
<td>Rs.20000</td>
<td><input type = "text" id = "ref" size = "2"/>
</td>
</tr>
<tr>
<th>Diwana</th>
<td>Rs.15000</td>
<td><input type = "text" id = "diw" size = "2"/>
</td>
</tr>
</table>
<p>
From the desk of Roopa R ,S.G.T College,Ballari. Page 9
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
<input type = "button" value = "Total Cost"
onclick = "computeCost();"/>
<input type = "text" size = "5" id = "cost"
onfocus = "[Link]();"/>
</p>
<p>
<input type = "submit" value = "Submit Order"/>
<input type = "reset" value = "Clear Order Form"/>
</p>
</form>
</body>
</html>
//[Link]
function computeCost()
{
var tv =[Link]("tv").value;
var ref = [Link]("ref").value;
var diw = [Link]("Diw").value;
[Link]("cost").value = totalCost = tv*25000 + ref*20000 + diw*15000; }
VALIDATING FORM INPUT
One of the common uses of JavaScript is to check the values provided in forms by users to
determine whether the values are sensible.
When a user fills in a form input element incorrectly and a JavaScript event handler function
detects the error, the function should produce an alert message indicating the error to the
user and informing the user of the correct format for the input.
The form in the next example includes the two password input elements, along with Reset and
Submit buttons.
The JavaScript function that checks the passwords is called either when the Submit button is
pressed, using the onsubmit event to trigger the call, or when the second text box loses focus,
using the blur event.
The function performs two different tests.
o First, it determines whether the user typed the initial password (in the first input
box) by testing the value of the element against the empty string. If no password has
been typed into the first field, the function calls alert to produce an error message and
returns false.
o The second test determines whether the two typed passwords are the same. If they
are different, once again the function calls alert to generate an error message and
returns false.
o If they are the same, it returns true.
//pswd_chk.html
<html>
<head>
<title>Password Checking</title>
<script type = "text/javascript" src = "pswd_chk.js">
</script>
</head>
<body>
<h3>Password Input</h3>
<form id="myForm" action=" ">
<p>
From the desk of Roopa R ,S.G.T College,Ballari. Page 10
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
<label>Your Password:<input type="password" id="initial" size="10"/></label><br/><br/>
<label>Verify Password:<input type="password" id="final" size="10"/></label><br/><br/>
<input type="reset" name="Reset"/>
<input type="submit" name="Submit"/>
</p>
</form>
<script type = "text/javascript" src = "pswd_chkr.js">
</script>
</body>
</html>
//pswd_chk.js
function chkPass( )
{
var init=[Link]("initial");
var fin=[Link]("final");
if([Link]=="")
{
alert("You did not enter a Password\n" + "Please enter atleast now");
[Link]( );
return false;
}
if([Link]!=[Link])
{
alert("The passwords you entered do not match ... Try Again");
[Link]( );
[Link]( );
return false;
}
Else return true;
}
OUTPUT:
We now consider an example that checks the validity of the form values for a name and phone
number obtained from text boxes. The pattern for matching names [LastName, FirstName,
MiddleName] is as follows:
/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/
The pattern for phone numbers is as follows:
/^d{3}-\d{8}$/
The following is the XHTML document, [Link], that displays the text boxes for a customer’s name
and phone number:
From the desk of Roopa R ,S.G.T College,Ballari. Page 11
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
//[Link]
<html>
<head>
<title>Name and Phone check</title>
<script type = "text/javascript" src = "[Link]">
</script>
</head>
<body>
<h3>enter your details</h3>
<form action="">
<p>
<label><input type="text" id="custName"/>Name(last name, first name, middle initial)</label><br/><br>
<label><input type="text" id="custPhone"/>Phone (ddd-dddddddd)</label><br/><br>
<input type="reset" id="reset"/>
<input type="submit" id="submit"/>
</p>
</form>
<script type = "text/javascript">
[Link]("custName").onchange=chkName;
[Link]("custPhone").onchange=chkPhone;
</script>
</body>
</html>
//[Link]
function chkName()
{
var myName = [Link]("custName");
var pos = [Link](/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if(pos != 0)
{
alert("The name you entered (" + [Link] + ") is not in the correct form. \n" +
"The correct form is: " + "last-name, first-name, middle-initial \n" +
"Please go and fix your name"); [Link]();
[Link]();
return false;
}
else return true;
}
function chkPhone()
{
var myPhone = [Link]("custPhone");
var pos = [Link](/^\d{3}-\d{8}$/);
if(pos != 0)
{
alert("The phone you entered (" + [Link] + ") is not in the correct form.\n" +
"The correct form is: " + "ddd-dddddddd \n" +"Please go and fix your phone number");
[Link]();
[Link]();
return false;
From the desk of Roopa R ,S.G.T College,Ballari. Page 12
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
}
else return true;
}
OUTPUT:
THE DOM 2 EVENT MODEL
The DOM 2 model is a modularized interface. One of the DOM 2 modules is Events, which includes
several sub-modules. The ones most commonly used are HTMLEvents and MouseEvents. The
interfaces and events defined by these modules are as follows:
EVENT PROPAGATION:
A browser which understands DOM, on receiving the XHTML document from the server,
creates atree known as document tree.
The tree constructed consists of elements of the document except the HTML
The root of the document tree is document object itself
The other elements will form the node of the tree
In case of DOM2, the node which generates an event is known as target node
Once the event is generated, it starts the propagation from root node
During the propagation, if there are any event handlers on any node and if it is enabled
then event handler is executed
The event further propagates and reaches the target node.
When the event handler reaches the target node, the event handler gets executed
After this execution, the event is again re-propagated in backward direction
During this propagation, if there are any event handlers which are enabled, will be executed.
The propagation of the even from the root node towards the leaf node or the target node is
known as
capturing phase.
The execution of the event handler on the target node is known as execution phase.
This phase is similar to event handling mechanism in DOM – 0
From the desk of Roopa R ,S.G.T College,Ballari. Page 13
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
The propagation of the event from the leaf or from the target node is known as bubbling phase
All events cannot be bubbled for ex: load and unload event
If user wants to stop the propagation of an event, then stop propagation has to be executed.
EVENT REGISTRATION:
In case of DOM2, the events get registered using an API known as addEventListener
The first arg is the eventName. Ex: click, change, blur, focus
The second arg is the event handler function that has to be executed when there is an event
The third arg is a Boolean argument that can either take a true or false value
If the value is true, it means event handler is enabled in capturing phase
If the event value if off (false), then event handler is enabled at target node
The addEventListener method will return event object to event handler function. The event
object can be accessed using the keyword “Event”
The address of the node that generated event will be stored in current target, which is
property of
event object
AN EXAMPLE OF THE DOM 2 EVENT MODEL
The next example is a revision of the [Link] document and [Link] script from previous example,
which used the DOM 0 event model. Because this version uses the DOM 2 event model, it does not work with
IE8.
//[Link]
<html>
<head>
<title>Illustrate form input validation with DOM 2</title>
<script type = "text/javascript" src = "[Link]">
</script>
</head>
<body>
<h3>enter your details</h3>
<form action="">
<p>
<label><input type="text" id="custName"/>Name(last name, first name, middle initial)</label><br/><br>
<label><input type="text" id="custPhone"/>Phone (ddd-dddddddd)</label><br/><br>
<input type="reset" />
<input type="submit" id="submitButton"/>
</p>
</form>
<script type = "text/javascript" src = "[Link]"/>
</body>
</html>
//[Link]
function chkName(event)
{
var myName = [Link];
var pos = [Link](/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if(pos != 0)
{
alert("The name you entered (" + [Link] + ") is not in the correct form.\n" +
"The correct form is: " + "last-name, first-name, middle-initial \n" + "Please go and fix your name");
[Link]();
From the desk of Roopa R ,S.G.T College,Ballari. Page 14
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
[Link]();
}
}
function chkPhone(event)
{
var myPhone = [Link];
var pos = [Link](/^\d{3}-
\d{8}$/); if(pos != 0)
{
alert("The phone you entered (" + [Link] + ") is not in the correct form.\n" +
"The correct form is: " + "ddd-dddddddd \n" +"Please go and fix your phone number");
[Link]();
[Link]();
}
}
//[Link]
var c =
[Link]("custName"); var
p = [Link]("custPhone");
[Link]("change",chkName,false)
;
[Link]("change",chkPhone,false
);
THE navigator OBJECT
The navigator object indicates which browser is being used to view the XHTML document. The
browser’s name is stored in the appName property of the object. The version of the browser is
stored in the appVersion property of the object. These properties allow the script to determine
which browser is being used and to use
processes appropriate to that browser. The following example illustrates the use of navigator, in
this case just to display the browser name and version number:
//[Link] file
<html>
<head>
<title>Navigator</title>
<script type = "text/javascript" src = "[Link]">
</script>
</head>
<body onload = "navProperties()">
</body>
</html>
//[Link] file
function
navProperties()
{
alert("the browser is: " + [Link] +
"\n" + "the version number is: " +
[Link] + "\n");
}
From the desk of Roopa R ,S.G.T College,Ballari. Page 15
UNIT -4 JavaScript and HTML Documents Web Designing BCA I Sem NEP
OUTPUT:
Mozilla Firefox Internet Explorer
DOM TREE TRAVERSAL
The parent Node property has the DOM address of the parent node of the node through which it is
referenced. The child Nodes property is an array of the child nodes of the node through which it is
referenced.
The previous Sibling property has the DOM address of the previous sibling node of the node through
which it is referenced. The next Sibling property has the DOM address of the next sibling node of the
node through which it is referenced.
The first Child and last Child properties have the DOM addresses of the first and last child nodes,
respectively, of the node through which they are referenced. The node Type property has the type of
the node through which it is referenced.
DOM TREE MODIFICATION
A number of methods allow JavaScript code to modify an existing DOM tree structure. The insert
Before(new Child, ref Child) method places the new Child node before the ref Child node. The replace
Child(new Child, old Child) method replaces the old Child node with the new Child node.
The remove Child(old Child) method removes the specified node from the DOM structure. The
append Child (new Child) method adds the given node to the end of the list of siblings of the node
through which it is called.
From the desk of Roopa R ,S.G.T College,Ballari. Page 16