Unit 3 (JavaScript and HTML Documents)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Unit 3

JAVASCRIPT AND HTML DOCUMENTS

By: Girish M
THE JAVASCRIPT EXECUTION ENVIRONMENT
• A browser displays an XHTML document in a window on the screen of the client.
• The JavaScript Window object 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 Window object has a property named document, which is a reference to the
Document object 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.
• Document objects also have property arrays for anchors, links, images, and applets.

By: Girish M
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. By: Girish M
DOM tree structure

• 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”> By: Girish M
ELEMENT ACCESS IN JAVASCRIPT
Method 1: Use of forms and elements array of document object
Method 2: Use of element names for DOM Addressing
Method 3: Element addressing can be done using javascript method
getElementById().
Method 4:check box group and radio button group

By: Girish M
Method 1: Use of forms and elements array of document
object
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 forms and elements arrays of the Document object, which is
referenced through the document property of the Window object.
<html>

<head>

<title>Access to form elements</title>

</head>

<body>

<form action=“”>

<input type=“button” name =“turnItOn”/>

</form>

</body>
By: Girish M
Method 2:Use of element names for DOM Addressing
• The DOM address of the button in this example, using the forms and elements arrays, is as follows:
• var dom = document.forms[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.

<html>
<head> Using the name attributes, the button’s DOM
<title>Access to form elements</title> address is as follows:
</head>
<body> var dom = document.myForm.turnItOn;
<form name =“myform” action=“”>
<input type=“button” name =“turnItOn”/>
</form>
</body>
</html>

By: Girish M
Method 3:Element addressing can be done using javascript
method getElementById().

• 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 = document.getElementById(“turnItOn”);

By: Girish M
Method 4

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:

By: Girish M
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.
By: Girish M
BASIC CONCEPTS OF EVENT HANDLING
• 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 lowercase letters.
• 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.

By: Girish M
EVENTS, ATTRIBUTES, AND TAG
Event Tag Attribute
blur onblur
change onchange
click onclick
dblclick ondblclick
focus onfocus
keydown onkeydown
keyup onkeypress
load onload
mousedown onmousedown
mousemove onmousemove
mouseout onmouseout
mouseup onmouseup
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.
By: Girish M
By: Girish M
As mentioned previously, 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:

By: Girish M
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:
<html>
<head>
<title>
handling of load events
</title>
<script type="text/javascript">
function loadgreeting()
{
alert(" you are visiting the home page of \n" +"SriDevaraj Urs
institute of management \n" +
"WELCOME !");
}
</script>
</head>
<body onload="loadgreeting();">
</body>
</html>

By: Girish M
HANDLING EVENTS FROM BUTTON ELEMENTS

Buttons in a Web document provide an effective way to collect simple


input from the browser user. Example:

By: Girish M
radio_click.html
<html>
<head>
<title> radio_click.html</title>
<script type = "text/javascript" src = "radio_click.js">
</script> radio_click.js
</head>
<body> function dChoice(ch)
<h4> Choose your favourite Director in Kannada Film {
Industry</h4> switch(ch)
<form id = "myForm" action = " "> {
<p> case 1: alert("Mungaaru Male"); break;
<label><input type = "radio" name = "dButton" value = "1" case 2: alert("Duniya"); break;
onclick = "dChoice(1)"/> Yogaraj Bhat</label><br/> case 3: alert("Eddelu Manjunatha"); break;
<label><input type = "radio" name = "dButton" value = "2" case 4: alert("Milana"); break;
onclick = "dChoice(2)"/> Suri</label><br/> default: alert("Ooops..Invalid choice :O"); break;
<label><input type = "radio" name = "dButton" value = "3" }
onclick = "dChoice(3)"/> Guru Prasad</label><br/> }
<label><input type = "radio" name = "dButton" value = "4"
onclick = "dChoice(4)"/> Prakash</label>
</p>
</form>
</body>
</html> By: Girish M
OUTPUT

By: Girish M
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:

radio_click2r.js
var dom = document.getElementById("myForm");
dom.getElementById("1").onclick = dChoice;
dom.getElementById("2").onclick = dChoice;
dom.getElementById("3").onclick = dChoice;
dom.getElementById("4").onclick = dChoice;

By: Girish M
<html> radio_click2.html
<head> radio_click2.js
<title> radio_click2.html</title>
<script type = "text/javascript" src = "radio_click2.js"> function dChoice(ch)
</script> {
</head> var dom = document.getElementById("myForm");
<body> for(var index = 0; index < dom.dButton.length; index++)
<h4> Choose your favourite Director in Kannada Film Industry</h4> {
<form id = "myForm" action = " "> if(dom.dButton[index].checked)
<p> {
<label><input type = "radio" name = "dButton" value = "1" id = ch = dom.dButton[index].value; break;
"1"/> Yogaraj Bhat</label><br/> }
<label><input type = "radio" name = "dButton" value = "2" id = }
"2"/> Suri</label><br/> switch(ch)
<label><input type = "radio" name = "dButton" value = "3" id = {
"3"/> Guru Prasad</label><br/> case 1: alert("Mungaaru Male"); break;
<label><input type = "radio" name = "dButton" value = "4" id = case 2: alert("Duniya"); break;
"4"/> Prakash</label> case 3: alert("Eddelu Manjunatha"); break;
</p> case 4: alert("Milana"); break;
</form> default: alert("Ooops..Invalid choice :O"); break;
<script type = "text/javascript" src = "radio_click2r.js"> }
</script> }
</body>
</html> By: Girish M
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 during use.

By: Girish M
HANDLING EVENTS FROM TEXT BOX AND
PASSWORD ELEMENTS
Text boxes and passwords can create four different events: blur, focus,
change, and select.

nochange.js
function computeCost()
{
var chicken = document.getElementById("chicken").value;
var mutton = document.getElementById("mutton").value;
var fish = document.getElementById("fish").value;

document.getElementById("cost").value = totalCost =
chicken*150
+ mutton*250 + fish*100;
}
By: Girish M
<tr>
nochange.html <th>Mutton Kaima (half)</th>
<html> <td>Rs. 250</td>
<head><title>nochange.html</title> <td><input type = "text" id = "mutton" size = "2"/></td>
<script type = "text/javascript" src = "nochange.js"> </tr>
</script> <tr>
</head> <th>Fish Fry (2 pieces)</th>
<body> <td>Rs. 100</td>
<form action = " "> <td><input type = "text" id = "fish" size = "2"/></td>
<h3> Non-Veg Items Order Form</h3> </tr>
<table border="border"> </table>
<tr> <p>
<th>Item</th> <input type = "button" value = "Total Cost" onclick =
<th>Price</th> "computeCost();"/>
<th>Quantity</th> <input type = "text" size = "5" id = "cost" onfocus =
</tr> "this.blur();"/>
<tr> </p>
<th>Chicken Kabab (full)</th> <p>
<td>Rs. 150</td> <input type = "submit" value = "Submit Order"/>
<td><input type = "text" id = "chicken" size = <input type = "reset" value = "Clear Order Form"/>
"2"/></td> </p>
</tr> </form>
</body>
</html>
By: Girish M
OUTPUT
After taking the entries, we get,

By: Girish M
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 on submit event to trigger the call, or when the second text box loses
focus, using the blur event.

By: Girish M
The function performs two different tests.
• 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.
• 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.
• If they are the same, it returns true.

By: Girish M
pswd_chk.html
pswd_chk.js
<html>
function chkPass( )
<head>
{
<title>Password Checking</title>
var init=document.getElementById("initial"); var
<script type = "text/javascript" src = "pswd_chk.js">
fin=document.getElementById("final");
</script>
if(init.value=="")
</head>
{
<body>
alert("You did not enter a Password\n" + "Please enter atleast
<h3>Password Input</h3>
now");
<form id="myForm" action=" ">
init.focus( ); return false;
<p>
}
<label>Your Password: <input
type="password" id="initial"
size="10"/></label><br/><br/> if(init.value!=fin.value)
<label>Verify Password: <input {
type="password" id="final" alert("The passwords you entered do not match. Try
size="10"/></label><br/><br/> Again");
<input type="reset" name="Reset"/> init.focus( );
<input type="submit" name="Submit"/> init.select( );
</p> return false;
</form> }
</body> Else return true;
</html> }
By: Girish M
By: Girish M
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}$/

By: Girish M
Example to validate Name and Phone Number
validator.html

<html>
<head>
<title>Name and Phone check</title>
<script type = "text/javascript" src = "validator.js">
</script> <script type = "text/javascript">
</head> document.getElementById("custName").onchange=chkName;
<body> document.getElementById("custPhone").onchange=chkPhone;
<h3>enter your details</h3> </script>
<form action=""> </body>
<p> </html>
<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>

By: Girish M
validator.js

function chkName() function chkPhone()


{ {
var myName = document.getElementById("custName"); var myPhone = document.getElementById("custPhone"); var
var pos = myName.value.search(/^[A-Z][a-z]+, ?[A-Z][a-z]+, pos = myPhone.value.search(/^\d{3}-\d{8}$/); if(pos != 0)
?[A-Z]\.?$/); if(pos != 0) {
{ alert("The phone you entered (" + myPhone.value + ") is not in
alert("The name you entered (" + myName.value + ") is not in the correct form.\n" + "The correct form is: " + "ddd-dddddddd
the correct form.\n" + "The correct form is: " + "last-name, first- \n" +
name, middle-initial \n" + "Please go and fix your phone number"); myPhone.focus();
"Please go and fix your name"); myName.focus(); myPhone.select(); return false;
myName.select(); return false; }
} else return true;
else return true; }
}

By: Girish M
Output

By: Girish M
THE DOM 2 EVENT MODEL

THE DOM 2 EVENT MODEL SPECIFICATION

• Describes a standard way to create, capture ,handle and


cancel events in a tree like structure such as an XHTML
documents object hierarchy

• It also describes event propagation behavior that is how an


event arrives as its target and what happens to it afterward

By: Girish M
EVENT PROPAGATION
• A browser which understands DOM, on receiving the XHTML document from the server, creates a
tree 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.

By: Girish M
EVENT PROPAGATION
• 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
• 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.

By: Girish M
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 eventhandler 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.

By: Girish M
Event 1 Top most Element Event 6

Child Element Bubbling phase


Capturing Phase Event 2 Event 5

Descendant
Element

Event 3 Event 4

Target Phase
By: Girish M
Document

<html>

<body>
Capturing Bubbling
phase(1) Phase (3)
<tabe>

<tbody>

<tr> Target
Phase(2) <tr>

<td> <td> <td> <td>

ABC DEF GHI JKL

By: Girish M
AN EXAMPLE OF THE DOM 2 EVENT MODEL
validator2.js
function chkName(event)
{
validator2.html var myName = event.currentTarget;
<html> var pos = myName.value.search(/^[A-Z][a-z]+,
<head> ?[A-Z][a-z]+, ?[A-Z]\.?$/); if(pos != 0)
{
<title>Illustrate form input validation with DOM 2</title>
alert("The name you entered (" + myName.value + ") is not
<script type = "text/javascript" src = "validator2.js"> in the correct form.\n" + "The correct form is: " + "last-
</script> name, first-name, middle-initial \n" +
</head> "Please go and fix
<body> your name");
<h3>enter your details</h3> myName.focus();
<form action=""> myName.select();
<p> }
}
<label><input type="text" id="custName"/>Name(last name, first function chkPhone(event)
name, middle initial)</label><br/><br> {
var myPhone = event.currentTarget;
<label><input type="text" id="custPhone"/>Phone (ddd-
var pos =
dddddddd)</label><br/><br> myPhone.value.search(/^\d{3}-
<input type="reset" /> \d{8}$/); if(pos != 0)
<input type="submit" id="submitButton"/> {
</p> alert("The phone you entered (" + myPhone.value + ") is
</form> not in the correct form.\n" + "The correct form is: " +
<script type = "text/javascript" src = "validator2r.js"/> "ddd-dddddddd \n" +
</body> "Please go and fix your
</html> phone number");
myPhone.focus();
myPhone.select();
}
} By: Girish M
validator2r.js

var c = document.getElementById("custName");
var p = document.getElementById("custPhone");
c.addEventListener("change",chkName,false);
p.addEventListener("change",chkPhone,false);

By: Girish M
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:

navigate.html file
navigate.js file
<html>
<head>
function navProperties()
<title>Navigator</title>
{
<script type = "text/javascript" src = "navigate.js">
alert("the browser is: " + navigator.appName + "\n"
</script>
+ "the version number is: " + navigator.appVersion
</head>
+ "\n");
<body onload = "navProperties()">
}
</body>
</html>

By: Girish M
Canvas Element
• The HTML5 <canvas> tag is used to draw graphics, with the JavaScript.
• The <canvas> element has no drawing abilities of its own (it is only a container for graphics). We
must use a script to actually draw the graphics.
• The getContext() method returns an object that provides methods and properties for drawing on the
canvas.
• getContext(“2d”) object which can be used to draw text, lines, boxes ,circles and more on the
canvas.
• The canvas element creates a rectangle into which can be drawn bit-mapped graphics using
JavaScript. It usually includes three attributes height, width, and id.
• The attributes for height and width are given non negative values which specifies the dimensions
of rectangle.
• The default values of height and width are 150 and 300 respectively.
• The content of canvas element is displayed when the browser does not support canvas.
By: Girish M
<html> function myFunction()
<head> {
var x=document.createElement("CANVAS");
<style> var ctx=x.getContext("2d");
canvas ctx.fillStyle="#00FF00";
ctx.fillRect(20,20,150,100);
{ }
border:1px solid black; </script>
</body>
}
</html>
</style>
</head>
<body>
<button onclick="myFunction()">create canvas and draw green
rectangle</button>
<p> cllick the buttom to create a CANVAS element with a green
rectangle</p>
<script>

By: Girish M

You might also like