Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 76

IV UNIT JAVASCRIPT

JavaScript HTML DOM Document


The HTML DOM document object is the owner of all other objects in your web
page.

The HTML DOM Document Object

The document object represents your web page.

If you want to access any element in an HTML page, you always start
with accessing the document object.

Below are some examples of how you can use the document object to
access and manipulate HTML.

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Property Description

element.innerHTML =  new html content Change the inner HTML of an element

Change the attribute value of an HTML


element.attribute = new value
element

element.style.property = new style Change the style of an HTML element


Method Description

Change the attribute value of an HTML


element.setAttribute(attribute, value)
element

Adding and Deleting Elements


Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

Adding Events Handlers


Method Description

document.getElementById(id).onclick = Adding event handler code to an onclick


function(){code} event

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object
collections, and properties. These are still valid in HTML5.

Later, in HTML DOM Level 3, more objects, collections, and properties


were added.
Property Description DOM

Returns all <a> elements that have a name


document.anchors 1
attribute

Returns all <applet> elements (Deprecated in


document.applets 1
HTML5)

Returns the absolute base URI of the


document.baseURI 3
document

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

Returns the domain name of the document


document.domain 1
server

document.domConfig Obsolete. Returns the DOM configuration 3

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements

JavaScript HTML DOM


With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
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:


The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create
dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

Accessing Elements in the DOM


The document object represents a web document or page. It represents a
document as a hierarchical tree structure and each element in the
document tree is called a Node in the DOM (Document Object Model).

Structurally, the Document Object Model consists of nodes, with each


node representing content in the web document. It gives developers a
way of representing everything on a web page so that the contents of the
web page is accessible via a common set of properties and methods.
DOM Methods

The getElementById() and getElementsByTagName() were the two


methods from DOM standard and the HTML5 specification adds three
new methods for accessing elements, getElementsByClassName(),
querySelector(), and querySelectorAll().
1)getElementById()

Typically you want to access an element within the DOM directly and
try to do something with it. Javascript provides a
document.getElementById() method, which is the easiest way to access
an element from the DOM tree structure. It will return the element that
has the ID attribute with the specified value.

document.getElementById("ID");

example:

<!DOCTYPE html>

<html>

<body>

<h1 id="heading">Document Object Model</h1>

<button onclick="changeIt()">Get Value</button>


<script>

function changeIt() {

alert(document.getElementById("heading").innerHTML);

</script>

</body>

</html>
2)getElementsByTagName

The getElementsByTagName() is one of the method exposes for


accessing nodes directly. This method takes a tag name as argument and
returns a collection of all the nodes it finds in the document that are a
sort of tag.

document.getElementsByTagName("TagName");

example:

<!DOCTYPE html>

<html>

<body>

<p>Paragraph 1</p>

<p>Paragraph 2</p>

<p>Paragraph 3</p>

<p>Paragraph 4</p>
<button onclick="count()">Get Value</button>

<script>

function count() {

var cnt = document.getElementsByTagName("p");

alert(cnt.length);

</script>

</body>

</html>

3) getElementsByClassName()
The getElementsByClass() method works same like
getElementById() method, and it will returns a collection
of all elements in the document with the specified class
name.
document.getElementsByClassName("ClassName");
example:
<!DOCTYPE html>
<html>
<body>
<p class="testClass">Paragraph 1</p>
<p class="testClass">Paragraph 2</p>
<p class="testClass">Paragraph 3</p>
<p class="testClass">Paragraph 4</p>
<button onclick="count()">Change Value</button>
<script>
function count() {
var tmpClass =
document.getElementsByClassName("testClass");
alert(tmpClass.length);
tmpClass[1].innerHTML ="Second Paragraph";
}
</script>
</body>
</html>
4) querySelector()

It will returns the first element that matches a specified CSS selector in
the document.

<!DOCTYPE html>
<html>
<body>
<p id="testQuery">Paragraph 1</p>
<p id="testQuery">Paragraph 2</p>
<p id="testQuery">Paragraph 3</p>
<p id="testQuery">Paragraph 4</p>
<button onclick="change()">Change Value</button>
<script>
function change() {
document.querySelector("#testQuery").innerHTML ="First
Paragraph";
}
</script>
</body>
</html>
5)querySelectorAll()

The querySelectorAll() method returns a collection filled with the


matching elements in source order. Since it is a static collection, the
modification of the document has no effect on the collection
Example:
<!DOCTYPE html>

<html>

<body>

<div id="div_">div content 1</div>

<p id="p_">Paragraph 2</p>

<button onclick="change()">Change Value</button>

<script>

function change() {

var elements = document.querySelectorAll("div,p");

elements[1].innerHTML = "content changed";

</script>

</body>

</html>

JavaScript - Events
What is an Event ?

JavaScript's interaction with HTML is handled through events that occur


when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Other examples include events like pressing
any key, closing a window, resizing a window, etc.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

onclick Event Type

This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning
etc., against this event type.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value =
"Say Hello" />
</form>
</body>
</html>

onsubmit Event Type

onsubmit is an event that occurs when you try to submit a form. You
can put your form validation against this event type.
Example

The following example shows how to use onsubmit. Here we are calling
a validate() function before submitting a form data to the webserver. If
validate() function returns true, the form will be submitted, otherwise it
will not submit the data.
Try the following example.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return
validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

onmouseover and onmouseout

These two event types will help you create nice effects with images or
even with text as well. The onmouseover event triggers when you bring
your mouse over any element and the onmouseout triggers when you
move your mouse out from that element. Try the following example.

Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the
result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

Handling Events from Body Elements


Example: the load event - triggered when the loading of a document is
completed
<!DOCTYPE html>
<!-- load.html
A document for load.js
-->
<html lang = "en">
<head>
<title> load.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "load.js" >
</script>
</head>
<body onload="load_greeting();">
<!-- use the onload attribute of <body> to specify the event
handler. -->
<p />
</body>
</html>

// load.js
// An example to illustrate the load event

// The onload event handler

function load_greeting () {
alert("You are visiting the home page of \n" +
"Pete's Pickled Peppers \n" + "WELCOME!!!");
}

Button elements in javascript:


Button Object

The Button object represents an HTML <button> element.

Access a Button Object

You can access a <button> element by using getElementById():

Example
var x = document.getElementById("myBtn");

Create a Button Object

You can create a <button> element by using the document.createElement() method:

<!DOCTYPE html>

<html>

<body>

<p>Click the "Try it" button to create a BUTTON element with a "Click
me" text.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction() {
var x = document.createElement("BUTTON");

var t = document.createTextNode("Click me");

x.appendChild(t);

document.body.appendChild(x);

</script>

</body>

</html>
Button Object Properties
Property Description

Sets or returns whether a button should automatically get focus when the page
autofocus
loads, or not

disabled Sets or returns whether a button is disabled, or not

form Returns a reference to the form that contains a button

formAction Sets or returns the value of the formaction attribute of a button

formEnctype Sets or returns the value of the formenctype attribute of a button

formMethod Sets or returns the value of the formmethod attribute of a button

formNoValidate Sets or returns whether the form-data should be validated or not, on submission

formTarget Sets or returns the value of the formtarget attribute of a button

name Sets or returns the value of the name attribute of a button

type Sets or returns the type of a button

value Sets or returns the value of the value attribute of a button


Text box and Password elements in javascript:
Input Text Object

The Input Text object represents an HTML <input> element with type="text".

Access an Input Text Object

You can access an <input> element with type="text" by using getElementById():

Example
var x = document.getElementById("myText");

<!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a Text Field</h3>

<input type="text" id="myText" value="Some text...">

<p>Click the "Try it" button to get the text in the text field.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Input Password Object

The Input Password object represents an HTML <input> element with type="password".

Access an Input Password Object

You can access an <input> element with type="password" by using getElementById():

Example
var x = document.getElementById("myPsw");

<!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a Password Field</h3>

Password: <input type="password" id="myPsw" value="psw123">

<p>Click the button to get the password of the password field.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.getElementById("myPsw").value;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Overview of the DOM Level 2 Event Model

The DOM Level 2 Event Model is designed with two main


goals. The first goal is the design of a generic event system
which allows registration of event handlers, describes event flow
through a tree structure, and provides basic contextual
information for each event. Additionally, the specification will
provide standard modules of events for user interface control
and document mutation notifications, including defined
contextual information for each of these event modules.
The second goal of the event model is to provide a common
subset of the current event systems used in DOM Level 0
browsers. This is intended to foster interoperability of existing
scripts and content. It is not expected that this goal will be met
with full backwards compatibility. However, the specification
attempts to achieve this when possible.
Terminology
UI events

User interface events. These events are generated by user


interaction through an external device (mouse, keyboard, etc.)

UI Logical events

Device independent user interface events such as focus change


messages or element triggering notifications.

Mutation events
Events caused by any action which modifies the structure of the
document.

Capturing

The process by which an event can be handled by one of the


event's target's ancestors before being handled by the event's
target.

Bubbling

The process by which an event propagates upward through its


ancestors after being handled by the event's target.

Cancelable

A designation for events which indicates that upon handling the


event the client may choose to prevent the DOM implementation
from processing any default action associated with the eve nt.

The DOM 2 Event Model


 Does not include DOM 0 features, but DOM 0 features are
still supported by browsers
 DOM 2 is modularized - one module is Events, which has
two submodules, HTMLEvents and MouseEvents, whose
interfaces are Event (blur, change, etc.) and MouseEvent
(click, mouseup, etc.)
 Event propagation
o The node of the document tree where the event is
created is called the target node
o The capturing phase (the first phase)
 Events begin at the root and move toward the
target node
 Registered and enabled event handlers at nodes
along the way are run
o The second phase is at the target node
 If there are registered but not enabled handlers
there for the event, they are run
o The third phase is the bubbling phase
 Event goes back to the root; all encountered
registered but not enabled handlers are run
 Not all events bubble (e.g., load and unload events do not
bubble. All of the mouse events bubble.)
 Any handler can stop further event propagation by calling
the stopPropagation method of the Event object
 DOM 2 model uses the Event object method,
preventDefault, to stop default operations, such as
submission of a form, if an error has been detected
 Event handler registration is done with the
addEventListener method
o Three parameters:

1. Name of the event, as a string literal


2. The handler function
3. A Boolean value that specifies whether the event
is enabled during the capturing phase
4. node.addEventListener("change",
chkName, false);
 A temporary handler can be created by registering it
and then unregistering it with removeEventListener
 The currentTarget property of Event always
references the object on which the handler is being
executed
 The MouseEvent interface (a subinterface of Event) has
two properties, clientX and clientY, that have the x and y
coordinates of the mouse cursor, relative to the upper left
corner of the browser window
 An example: A revision of validator, using the DOM
2 event model
<!DOCTYPE html>; // validator2.js
<!-- validator2.html // An example of input
A document for validation using the change and
validator2.js submit
Note: This // events, using the DOM 2
document works with event model
IE9, but not earlier // Note: This document does not
versions of work with IE8
IE
-->; //
<html lang = "en">; *********************************
<head>; ************************* //
<title>; // The event handler function for
Illustrate form input the name text box
validation with DOM
2>; </title>; function chkName(event) {
<meta charset =
"utf-8" />; // Get the target node of the
<script type = event
"text/javascript" src
= "validator2.js" >; var myName =
</script>; event.currentTarget;
</head>;
<body>; // Test the format of the input
<h3>; Customer name
Information </h3>; // Allow the spaces after the
<form action = commas to be optional
"">; // Allow the period after the
<p>; initial to be optional
<label>;
<input type var pos =
= "text" id = myName.value.search(/^[A-Z][a-z]
"custName" />; +, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
Name (last
name, first name, if (pos != 0) {
middle initial) alert("The name you entered
</label>; (" + myName.value +
<br />;<br />; ") is not in the
correct form. \n" +
<label>; "The correct form is: "
<input type +
= "text" id = "phone" "last-name, first-name,
/>; middle-initial \n" +
Phone number "Please go back and fix
(ddd-ddd-dddd) your name");
</label>; }
<br />;<br />; }

<input type = //
"reset" />; *********************************
<input type = ************************* //
"submit" id = // The event handler function for
"submitButton" />; the phone number text box
</p>;
</form>; function chkPhone(event) {
<script type =
"text/javascript" src // Get the target node of the
= "validator2r.js" >; event
</script>;
var myPhone =
</body>; event.currentTarget;
</html>;
// Test the format of the input
phone number
// validator2r.js
// The last part of var pos =
validator2. Registers myPhone.value.search(/^\d{3}-\d{3
the
// event handlers
// Note: This script
does not work with IE8

// Get the DOM }-\d{4}$/);


addresses of the
elements and register if (pos != 0) {
// the event handlers alert("The phone number you
entered (" + myPhone.value +
var customerNode ") is not in the
= correct form. \n" +
document.getElementByI "The correct form is:
d("custName"); ddd-ddd-dddd \n" +
var phoneNode = "Please go back and fix
document.getElementByI your phone number");
d("phone"); }
}
customerNode.addEventL
istener("change",
chkName, false);

phoneNode.addEventList
ener("change",
chkPhone, false);

NAVIGATOR OBJECT
Navigator Object

The navigator object contains information about the browser.


Note: There is no public standard that applies to the navigator
object, but all major browsers support it.
Navigator Object Properties
Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
Determines whether cookies are enabled in the
cookieEnabled
browser
Returns a Geolocation object that can be used to
geolocation
locate the user's position
language Returns the language of the browser
onLine Determines whether the browser is online
platform Returns for which platform the browser is compiled
product Returns the engine name of the browser
Returns the user-agent header sent by the browser to
userAgent
the server

Navigator Object Methods


Method Description
Specifies whether or not the browser has Java
javaEnabled()
enabled
Removed in JavaScript version 1.2. Specifies whether
taintEnabled()
the browser has data tainting enabled
DOM tree traversal and modification :
DOM traversing
DOM traversing, which means “move through”, are used to
“find” (or select) HTML elements based on their relation to
other elements. Here traversing happen in both direction top to
bottom or bottom to top. Start with one selection and move
through that selection until you reach the elements you desire.

Based on selection, we can easily move up (ancestors),


down (descendants) and sideways (siblings) in the tree,
starting from the selected (current) element. This
movement is called traversing – or moving through – the
DOM tree.
There are two jQuery methods for traversing down DOM tree

 children() – get all direct children of the selected element.


 find() – get descendant elements of the selected element, all
the way down to the last descendant.
Traversing – Siblings
There are seven jQuery methods for traversing sideways in the
DOM tree
 siblings() – get all sibling elements of the selected element.
 next() – get the next sibling element of the selected
element.
 nextAll() – get all next sibling elements of the selected
element.
 nextUntil() – get all next sibling elements between two two
elements.
 prev() – get get all previous sibling elements of the selected
element.
 prevAll() – get get all previous sibling elements of the
selected element.
 prevUntil() – get get all previous sibling elements between
two two elements.

DOM manipulating
 DOM manipulation includes creating, inserting, copying,
removing, of DOM structure. All of these methods are
referred to as “setters,” as they change the DOM structure.
A few methods like .attr(), .html(), and .val() are also act as
“getters,” retrieving information from DOM elements for
later use.
jQuery Manipulating – Inserting
jQuery provides following methods that allow us to inserting
elements in the DOM

 append() – inserts content at the end of the selected


elements
 prepend() – inserts content at the beginning of the selected
elements
 html() – sets or get the content (innerHTML) of the
selected elements.
 text() – sets or gets the text content of selected elements
 val() – sets or gets the value of form fields
 attr() – set or gets attribute values of an elements

Dynamic Documents with JavaScript


1. Dynamic HTML Documents
2. Element Positioning
3. Moving Elements
4. Element Visibility
5. Changing Colors and Fonts
6. Dynamic Content
7. Stacking Elements
8. Locating the Mouse Cursor
9. Reacting to a Mouse Click
10. Slow Movement of Elements
11. Dragging and Dropping an Element

Element Positioning

 HTML tables can used for element


positioning, but lack flexibility and are slow to
render

 CSS-P was released by W3C in 1997

 CSS-P allows placing of any element


anywhere on the display, and moving it later
 The position of any element can be dictated by
the three style properties:
position, left, and top

o The possible values of position are absolute,


relative, and static

o Absolute Positioning
o <p style = "position: absolute;
o left: 50px; top: 100px;">

 If an element is nested inside another element


and is absolutely positioned, the top and left
properties are relative to the enclosing element

Illustration of Nested Absolute Positioning


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN"
"http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">

<!-- absPos.html
An example to illustrate absolute Positioning of elements
-->
<html>
<head>
<title>
Absolute Positioning of elements
</title>
<style type = "text/css">
/* A style for a paragraph of text */

.regtext {font-family: Times; font-size: 14pt; width: 600px}


/* A style for the text to be absolutely positioned */

.abstext { position: absolute; top: 25px; left: 50px;


font-family:Times; font-size: 24pt;
font-style: italic; letter-spacing: 1em;
color: rgb(102,102,102,102); width: 500 px}

</style>

</head>

<body>
<p class="regtext">
The Snowy Owl (<i>Nyctea scandiaca</i>) is a bird of the Order Strigiformes.
It has a length of 20-27 in and a wingspan: 4.5-5 feet. Weight is 3.5-4.5
pounds.
Its Range is the Circumpolar; arctic regions of the old and new worlds.
Predatory feeder: eats small mammals, especially lemmings, birds,
fish and small marine mammals. Largely diurnal. Migrates to
southern Canada and the United States during years of lemming and
hare scarcity.

Breeds May-June, lays 2-14 eggs, number dependent upon the food
supply, at approximately 2-day intervals. Nest is scraped out of
the earth amid tall moss. The female incubates while the male
brings her food. Eggs hatch in 32-34 days. Young are covered in
white down. Fledging period between 50-55 days. Both parents feed
and tend the young, and are fiercely protective.
</p>

<p class = "abstext">


SNOWY OWL
<br /><br />
<i>Nyctea scandiaca</i>
</p>

</body>
</html>

 Relative Positioning
If no top and left properties are specified, the
element is placed exactly where it would have
been placed if no position property were given
But it can be moved later
 If top and left properties are given, they are
offsets from where it would have placed without
the position property being specified
 If negative values are given for top and left, the
displacement is upward and to the left
Can make superscripts and subscripts

Illustration of Relative Positioning


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN"
"http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">

<!-- absPos.html
Illustrates relative Positioning of elements
-->
<html>
<head>
<title>
Relative Positioning of elements
</title>

</head>

<body>
<p>
SNOWY <span style ="position: relative; top:10px;
font-family: Times; font-size:48pt;
font-style: italic; color: red;">
OWL </span> (<i>Nyctea scandiaca</i>)
</p>

</body>
</html>
 Static Positioning
1.The default value if position is not specified

2.Neither top nor left can be initially set, nor can


they be changed later
Moving Elements

 If position is set to either absolute or relative, the


element can be moved after it is displayed

 Change the top and left property values with a


script

Illustration of Moving Elements


mover.html
An example to illustrateng an element within a document
-->
<html>
<head>
<title>
Moving elements
</title>
<script type = "text/javascript">
<!--
// The event handler function to move and element

function moveIt(movee, newTop, newLeft) {


dom = document.getElementById(movee).style;
/* Change the top and left properties to perform the move
Note the addition of units to the input values */

dom.top = newTop + "px";


dom.left = newLeft + "px";
}
//-->
</script>
</head>

<body>
<form action ="">
<p>
x coordinate:<input type= "text" id ="leftCoord" size ="5" />
<br />
y coordinate: <input type= "text" id ="topCoord" size ="5" />
<br />
<input type= "button" value = "Move it" onclick =
"moveIt('850volvo',
document.getElementById('topCoord').value,
document.getElementById('leftCoord').value)" />
</P>
</form>

<div id ="850volvo" style = "position: absolute; top: 115 px; left: 0;">
<img src= "../volvopictures/850.jpg" alt="(Picture of an 850 Volvo)" />
</div>
</body>
</html>
Element Visibility:

 The visibility property of an element controls


whether it is displayed

 The values are visible and hidden

Suppose we want to toggle between hidden and


visible, and the element's DOM address is dom
if (dom.visibility == "visible"
dom.visibility = "hidden";
else
dom.visibility = "visible";

<!-- showHide.html
An example to illustrateng visibility control of elements
-->
<html>
<head>
<title>
Visibility Control
</title>
<script type = "text/javascript">
<!--
// The event handler function to toggle the visibility of the volvo
image

function flipImag() {
dom = document.getElementById("164volvo").style;
// Flip the visibility objective to whatever is not now
if (dom.visibility == "visible")
dom.visibility = "hidden";
else
dom.visibility = "visible";
}
//-->
</script>
</head>

<body>
<form action ="">

<div id ="164volvo" style = "position: relative;


visibility: "visible;">
<img src= "../volvopictures/164.jpg" alt="(Picture of an 164
Volvo)" />
</div>
<p>
<br />
<input type= "button" value = "Toggle car"
onclick = "flipImag()" />
</p>
</form>
</body>
</html>

Changing Colors and Fonts

 Background color is controlled by the


backgroundColor property

 Foreground color is controlled by the color


property

 Can use a function to change these two


properties
o Let the user input colors through text
buttons

o Have the text elements call the function


with the element address (its name) and
the new color

Background color:
o <input type = "text" size = "10"

o name = "background"

o onchange = "setColor('background',

o this.value)">

o The actual parameter this.value works


because at the time of the call, this is a
reference to the text box (the element in
which the call is made)

So, this.value is the name of the new color


 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN"
 "http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">



 <!-- dynColors.html

 An example to illustrate dynamic foreground and background colors

 -->

 <html>

 <head>

 <title> Dynamic Colors

 </title>

 <script type = "text/javascript">

 <!--

 // The onload event handler


 function setColor(where, newColor) {

 if (where == "background" )

 document.body.style.backgroundColor = newColor;

 else

 document.body.style.color = newColor;

 }

 //-->

 </script>
 </head>


 <body>

 <p style = " font-family: Times; font-style: italics;

 font-size: 24pt;">

 This document is designed to illustrate dynamic settings of the

 foreground and background colors.

 </p>


 <form action="">

 <p>

 Background color:

 <input type= "text" name="background" size ="10"

 onchange = "setColor('background', this.value)" />

 <br />

 Foreground color:

 <input type= "text" name="foreground" size ="10"

 onchange = "setColor('foreground', this.value)" />

 <br />

 </p>

 </form>

 </body>
 </html>

*Changing fonts
 We can change the font properties of a link by
using the mouseover and mouseout events to
trigger a script that makes the changes

 In this case, we can assign the complete script


to make the changes to the element

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN"


"http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">

<!-- dynLink.html
Illustrates mic font styles and colors for links
-->
<html>
<head>
<title>
Dynamic fonts for links
</title>
<style type ="text/css">
.regText { font: Times; font-size:16pt;}
</style>

</head>

<body>
<p class ="regText">
The female
<a style = "color: blue;"
onmouseover = "this.style.color = 'red';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'blue';
this.style.font = 'normal 16pt Times';" >
incubates </a>
while the male brings her food.
</p>

</body>
</html>

Dynamic Content

 The content of an HTML element is addressed


with the value property of its associated
JavaScript object

 An example to illustrate dynamic values

<!-- dynContent.html
An example to illustrate dynamic values
-->
<html>

<head>
<title> Dynamic values
</title>

<style type ="text/css">


.regText { font: Times; font-size:16pt;}
</style>

<script type = "text/javascript">


<!--
//
var helpers = ["Your name must be in the form: \n \
given name, initial., last name",
"Your email address must be in the form: user@domain",
"Your user ID must have at least six characters",
"Your passwd must have at least six characters, \
and it must include at least one digit",
"This box provides advice on filling out \
the form on this page. Put the mouse cursor over any \
input field and get advice"]
// ************************************************** //
// The event handler function to change the value of the textarea

function messages(adviceNumber){
document.getElementById("adviceBox").value =helpers[adviceNumber];
}

// ************************************************** //

//-->
</script>

</head>

<body>

<form action = "">


<p class ="regText">
Name: <input type = "text"
onmouseover = "messages(0)"
onmouseout = "messages(4)" />
<br />
<br />
<br />
Email: <input type = "text"
onmouseover = "messages(1)"
onmouseout = "messages(4)" />
<br />
<br />
To
<span style = "color: blue;"
onmouseover = "this.style.color = 'red';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'blue';
this.style.font = 'normal 16pt Times';" >
create
</span>
an account, please provide the following:
<br />
<br />
User ID: <input type = "text"
onmouseover = "messages(2)"
onmouseout = "messages(4)" />
<br />
<br />
<br />
Password: <input type = "text"
onmouseover = "messages(3)"
onmouseout = "messages(4)" />
<br />
<br />
<br />
<textarea id= "adviceBox" rows = "3" cols = "50"
style = "position: absolute; left: 250; top= 0">
</textarea>
</p>
</form>
</body>
</html>

Stacking Elements

 The top and left properties determine the


position of an element on the display screen,
which is a two-dimensional device

 Can create the appearance of a third


dimension by having overlapping elements,
one of which covers the others (like windows)

o Done with the z-index property, which


determines which element is in front and
which are covered by the front element

o The JavaScript variable associated with


the z-index property is zIndex
 The stacking order can be changed
dynamically

 Make the elements anchors, so they respond to


mouse clicking
o The href attribute can be set to call a
JavaScript function by assigning it the
call, with 'JAVASCRIPT' attached to the call code
o <a href = "JAVASCRIPT:fun()">

 The handler function must change the zIndex


value of the element

 A call to the function from an element sets the


zIndex value of the new ontop element to 10 and

the zIndex value of the old ontop element to 0


o It also sets the current ontop to the new
ontop
<!-- stacking.html
An example to illustrate dynamic stacking of images
-->
<html>

<head>
<title>
Dynamic stacking of images
</title>
<script type = "text/javascript">
<!--
var oldTop = "v130";
//
// ************************************************** //
/* The event handler function to move the given element to the
top of the stack.
*/

function toTop(newTop){
/* Set the two DOM addresses, one for the old top
element and one for the new top element
*/

domTop = document.getElementById(oldTop).style;
domNew = document.getElementById(newTop).style;

/* Set the index properties of the two elements, and


reset oldTop to new top */

domTop.zIndex = "0";
domNew.zIndex = "10";
oldTop = newTop;
}
// ************************************************** //
//-->
</script>

<style type ="text/css">


.auto1 {position:absolute; top: 0; left: 0; z-index: 0;}
.auto2 {position:absolute; top: 50px; left: 110px; z-index: 0;}
.auto3 {position:absolute; top: 100px; left: 220px; z-index: 0;}
.auto4 {position:absolute; top: 150px; left: 330px; z-index: 0;}
</style>

</head>

<body>
<p>
<img class = "auto1" id = "v130"
src="../volvopictures/130.jpg" width=500
alt="picture of a volvo 130"
onclick = "toTop('v130')" />

<img class = "auto2" id = "v164"


src="../volvopictures/164.jpg" width=500
alt="picture of a volvo 164"
onclick = "toTop('v164')" />

<img class = "auto3" id = "v1800"


src="../volvopictures/1800.jpg" width=500
alt="picture of a volvo 1800"
onclick = "toTop('v1800')" />

<img class = "auto4" id = "v240"


src="../volvopictures/240.jpg" width=500
alt="picture of a volvo 240"
onclick = "toTop('v240')" />

</p>

</body>
</html>

Locating the Mouse Cursor

 The coordinates of the element that caused an


event are available in the clientX and clientY
properties of the event object

o These are relative to upper left corner of


the browser display window
o screenX and screenY are relative to the upper left
corner of the whole client screen

 In order to locate the mouse cursor when the


mouse button is clicked, use the click event
<!-- where.html
An example to illustrate the position of the cursor
-->
<html>

<head>
<title>
Dynamic the position of the cursor
</title>
<script type = "text/javascript">
<!--
//
// ************************************************** //
/* The event handler function to get and display the
coordinates of the cursor, both in an element and
on the screen
*/

function findIt(evnt){
document.getElementById("xcoord1").value = evnt.clientX;
document.getElementById("ycoord1").value = evnt.clientY;
document.getElementById("xcoord2").value = evnt.screenX;
document.getElementById("ycoord2").value = evnt.screenY;
}
// ************************************************** //
//-->
</script>

</head>

<body onclick = "findIt(event)">

<form action = "">

<p>
Whitin the Client area <br />
x:
<input type = "text" id = "xcoord1" size = "4" />
y:
<input type = "text" id = "ycoord1" size = "4" />
Relative to the origin of the screen coordinate system:
x:
<input type = "text" id = "xcoord2" size = "4" />
y:
<input type = "text" id = "ycoord2" size = "4" />

</p>
</form>
<img src="../volvopictures/444.jpg" width=500 alt="picture of a
volvo 444" />

</p>

</body>
</html>

Reacting to a Mouse Click

 A mouse click can be used to trigger an action,


no matter where the mouse cursor is in the
display

 Use event handlers for onmousedown and onmouseup that


change the visibility attribute of the message

 An example to illustrate reactions to pressing


the mouse
<!-- anywhere.html
An example to illustrate reactions to the mouse
when it is pressed no matter where it is on the screen
-->
<html>

<head>
<title>
eacting to the mouse click
</title>
<script type = "text/javascript">
<!--
//
// ************************************************** //
/* The event handler function to display a message */
function displayIt() {

document.getElementById("message").style.visibility = "visible";

/* The event handler function to hide a message */

function hideIt() {

document.getElementById("message").style.visibility = "hidden";

}
// ************************************************** //
//-->
</script>

</head>

<body>

<p>

<span id= "message"


style = "color:red; visibility:hidden;
font-size: 20pt; font-style: italic;
font-weight: bold;">
Please do NOT click there!
</span>
<script type = "text/javascript">
<!--
//
// ************************************************** //
document.onmousedown =displayIt;
document.onmouseup =hideIt;
// ************************************************** //
//-->
</script>

</body>
</html>
Slow Movement of Elements

 To animate an element, it must be moved by


small amounts, many times, in rapid
succession

 JavaScript has two ways to do this, cover just


one here:
 setTimeout("fun()", n)

 Example: move a text element from its initial


position (100, 100) to a new position (300,
300)

1.Use the onload attribute of the body element


to initialize the position of the element

Set the x and y coordinates to the top and


left attributes of the element
2.Use a move function to change the top and
left attributes by one pixel in the direction

of the destination

3.A problem: coordinate properties are


stored as strings including the units
("150px")
 In order to do addition or subtraction
with the coordinate properties, convert
them to just numbers; the units must
be replaced before the properties are
used

4.Another problem: need to use some


HTML special characters ("<" and "--")
1.XML parsers may remove all
comments

2.Put the script in a CDATA section


3.Put JavaScript in separate file

. These are problems of validation only


Both IE6 and NS6 deal correctly with
comments
<!-- moveText.html
An example to illustrate moving text element
uses the JavaScript from file moveTextfuns.js
-->
<html>

<head>
<title>
Moving text
</title>
<script type = "text/javascript"
src = "moveTextfuns.js">
</script>

</head>

<!-- call the initialization function on load, giving the


destination coordinates for the text to be moved
-->

<body onload = "initText(300, 300)">

<!-- The text to be moved, including its initial position -->


<p>
<span id = 'theText'
style = "position: absolute; left: 100px; top: 100px;
font:bold 20pt 'Times Roman'; color:blue;">
Take a jump in the lake!
</span>
</p>

</body>
</html>

This moveTextfuns.js - used by moveText.html


var dom, x, y, finalx = 300, finaly = 300;

// *************************************************************
// A function to initialize the x and y coordinates
// of the current position of the text to be moved,
// and the call the mover function

function initText(){
dom = document.getElementById('theText').style;

/* Get the current positions of the text */

var x = dom.left;
var y = dom.top;

/* convert the string values of left and top to numbers by


stripping off the units */

x = x.match(/\d+/);
y = y.match(/\d+/);

/* call the function that moves it */

moveText(x,y);

} /*** end of fucntion initText */

// *************************************************************
// A function to move the text from its original position to
// (finalx, finaly)

function moveText(x,y){
/* If the x coordinates are not equal, move a to finalx */

if (x != finalx)
if( x > finalx) x--;
else if(x < finalx) x++;

/* If the y coordinates are not equal, move a to finaly */

if (y != finaly)
if( y > finaly) y--;
else if(y < finaly) y++;

/* As long as the text is not at the destination, call the


mover with the current position */

if (( x != finalx) || (y != finaly )){

/* Put the units back on the coordinates before assigning


them to the properties to cause the move */

dom.left = x + "px";
dom.top = y + "px";

/* recursive call, after a 1-millisecond delay */

setTimeout("moveText(" + x + "," + y + ")", 1);

} /*** end of moveText */

Dragging and Dropping an Element


 We can use mouseup, mousedown, and mousemove events to
grab, drag, and drop
 We know how to move an element - just
change its left and top properties
 Example: magnetic poetry

 The DOM 2 event model is required (the Event


object and its property, currentTarget)
 We use both DOM 0 and DOM 2 models
(DOM 0 to call the mousedown handler, grabber)

 We use three functions: grabber, mover, and dropper

 Drag and drop requires three processes:


1.Get dom of the element to be moved when the
mouse button is pressed down (onmousedown) while
the mouse cursor is over the element to be
moved
o If we want to move an element in a
display that has more than one element,
we must first determine which element the
mouse cursor is over

o We can get the id of an element on which


an event occurs with the srcElement property
of an event object; srcElement has a property
named id
o event.srcElement.id

is the id of the element on which the event


occurred

2.Move the element by changing its top and left


properties of the element as the mouse cursor
is moved (onmousemove)
o Use event.x and event.y to track the mouse
cursor

3.Dropping the element when the mouse button


is released by undefining the dom used to carry
out the move
Introduction to XML
What is XML?

 XML stands for eXtensible Markup Language


 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation

XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML).

XML tags identify the data and are used to store and organize the data, rather than specifying
how to display it like HTML tags, which are used to display the data. XML is not going to
replace HTML in the near future, but it introduces new possibilities by adopting many successful
features of HTML.

There are three important characteristics of XML that make it useful in a variety of systems and
solutions −

 XML is extensible − XML allows you to create your own self-descriptive tags, or
language, that suits your application.

 XML carries the data, does not present it − XML allows you to store the data
irrespective of how it will be presented.

 XML is a public standard − XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.

XML Usage

A short list of XML usage says it all −

 XML can work behind the scene to simplify the creation of HTML documents for large
web sites.

 XML can be used to exchange the information between organizations and systems.

 XML can be used for offloading and reloading of databases.

 XML can be used to store and arrange the data, which can customize your data handling
needs.

 XML can easily be merged with style sheets to create almost any desired output.
 Virtually, any type of data can be expressed as an XML document.

Anatomy of an XML:
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.

Let us see each component of the above diagram in detail.

XML Declaration

The XML document can optionally have an XML declaration. It is


written as follows −
<?xml version = "1.0" encoding = "UTF-8"?>

Where version is the XML version and encoding specifies the character
encoding used in the document.
Syntax Rules for XML Declaration

 The XML declaration is case sensitive and must begin with "<?
xml>" where "xml" is written in lower-case.

 If document contains XML declaration, then it strictly needs to be


the first statement of the XML document.

 The XML declaration strictly needs be the first statement in the


XML document.

 An HTTP protocol can override the value of encoding that you put
in the XML declaration.

Tags and Elements

An XML file is structured by several XML-elements, also called XML-


nodes or XML-tags. The names of XML-elements are enclosed in
triangular brackets < > as shown below −
<element>

Syntax Rules for Tags and Elements

Element Syntax − Each XML-element needs to be closed either with


start or with end elements as shown below −
<element>....</element>

or in simple-cases, just this way −


<element/>

Nesting of Elements − An XML-element can contain multiple XML-


elements as its children, but the children elements must not overlap. i.e.,
an end tag of an element must have the same name as that of the most
recent unmatched start tag.

The Following example shows incorrect nested tags −


<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint
</contact-info>
</company>

The Following example shows correct nested tags −


<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint</company>
<contact-info>

Root Element − An XML document can have only one root element.
For example, following is not a correct XML document, because both
the x and y elements occur at the top level without a root element −
<x>...</x>
<y>...</y>

The Following example shows a correctly formed XML document −


<root>
<x>...</x>
<y>...</y>
</root>

Case Sensitivity − The names of XML-elements are case-sensitive. That


means the name of the start and the end elements need to be exactly in
the same case.

For example, <contact-info> is different from <Contact-Info>

XML Attributes

An attribute specifies a single property for the element, using a


name/value pair. An XML-element can have one or more attributes. For
example −
<a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a>
Here href is the attribute name and http://www.tutorialspoint.com/ is
attribute value.
Syntax Rules for XML Attributes

 Attribute names in XML (unlike HTML) are case sensitive. That


is, HREF and href are considered two different XML attributes.

 Same attribute cannot have two values in a syntax. The following


example shows incorrect syntax because the attribute b is specified
twice

<a b = "x" c = "y" b = "z">....</a>

 Attribute names are defined without quotation marks, whereas


attribute values must always appear in quotation marks. Following
example demonstrates incorrect xml syntax

<a b = x>....</a>

In the above syntax, the attribute value is not defined in quotation marks.

XML References

References usually allow you to add or include additional text or markup


in an XML document. References always begin with the symbol "&"
which is a reserved character and end with the symbol ";". XML has
two types of references −

 Entity References − An entity reference contains a name between


the start and the end delimiters. For example &amp; where amp is
name. The name refers to a predefined string of text and/or
markup.
 Character References − These contain references, such as &#65;,
contains a hash mark (“#”) followed by a number. The number
always refers to the Unicode code of a character. In this case, 65
refers to alphabet "A".

XML Text

The names of XML-elements and XML-attributes are case-sensitive,


which means the name of start and end elements need to be written in
the same case. To avoid character encoding problems, all XML files
should be saved as Unicode UTF-8 or UTF-16 files.

Whitespace characters like blanks, tabs and line-breaks between XML-


elements and between the XML-attributes will be ignored.

Some characters are reserved by the XML syntax itself. Hence, they
cannot be used directly. To use them, some replacement-entities are
used, which are listed below −
Not Allowed Character Replacement Entity Character Description

< &lt; less than

> &gt; greater than

& &amp; ampersand

' &apos; apostrophe

" &quot; quotation mark

Creating XML Documents


To create a well-formed XML document with XML Notepad, follow
these steps:

1. To open XML Notepad, click Start, point to Programs, point to


Microsoft XML Notepad, and then click Microsoft XML Notepad.
The interface shows two panes. The Structure pane on the left
presents the beginning of an XML tree structure, with a
Root_Element and Child_Element already created. Empty text
boxes in the Values pane accept corresponding values.
2. Change Root_Element to Catalog and Child_Element to Book, and
add an attribute and three child elements to the Book child
element.NOTE: When you insert the following values, do not
include apostrophes. XML Notepad inserts them for you as your
XML document requires.

1. To insert an attribute for Book, right-click Book, point to


Insert, and click Attribute. Next to the cube icon, type ID. To
insert a value for this attribute, highlight ID and type Bk101
in the corresponding text box in the Values pane.
2. To insert a child element for Book, right-click the folder icon
next to Book, point to Insert, and click Child Element. A leaf
icon appears. Type Author next to this icon, and then type
Gambardella, Matthew in the corresponding text box in the
Values pane.
3. Add two more child elements: Title and Genre. Type XML
Developer's Guide and
Computer in the corresponding text boxes in the Values pane.
3. To add another Book child element to the Root node, right-click an
existing Book element and click Duplicate. Fill in the values as
needed.
4. To add text to existing elements, highlight the node for which you
would like to add a text node. On the Insert menu, click Text.
5. To add comments to existing elements, highlight the node after
which or in which you want to insert the comment. On the Insert
menu, click Comment. If the highlighted node is expanded, the
comment is inserted within the highlighted node. If the highlighted
node is collapsed, the comment is inserted after the highlighted
node.
6. To change a node's type, highlight the node that you want to
change. On the Tools menu, point to Change To and click the
appropriate type.

NOTE: You cannot change the type of the root node or of nodes
with children.
7. To view the XML source of the document, on the View menu,
click Source. The sample output resembles the following:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
text1
</book>
<!--Comment1-->
<book id="bk102">
<!--Comment2-->
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
</book>
</catalog>

Note the following message at the bottom of the View window:

The current XML definition is well formed.

Also, note that the XML declaration or processing instructions


must be added with an external editor, such as Notepad.

8. To save the XML document, on the File menu, click Save. To exit
XML Notepad, on the File menu, click Exit.

XML – DTDs
The XML Document Type Declaration, commonly known as DTD, is a
way to describe XML language precisely. DTDs check vocabulary and
validity of the structure of XML documents against grammatical rules of
appropriate XML language.

An XML DTD can be either specified inside the document, or it can be


kept in a separate document and then liked separately.

Syntax

Basic syntax of a DTD is as follows −


<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

In the above syntax,

 The DTD starts with <!DOCTYPE delimiter.

 An element tells the parser to parse the document from the


specified root element.

 DTD identifier is an identifier for the document type definition,


which may be the path to a file on the system or URL to a file on
the internet. If the DTD is pointing to external path, it is called
External Subset.

 The square brackets [ ] enclose an optional list of entity


declarations called Internal Subset.

Internal DTD

A DTD is referred to as an internal DTD if elements are declared within


the XML files. To refer it as internal DTD, standalone attribute in XML
declaration must be set to yes. This means, the declaration works
independent of an external source.
Syntax

Following is the syntax of internal DTD −


<!DOCTYPE root-element [element-declarations]>

where root-element is the name of root element and element-


declarations is where you declare the elements.
Example

Following is a simple example of internal DTD −


<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>

<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

Let us go through the above code −

Start Declaration − Begin the XML declaration with the following


statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>

DTD − Immediately after the XML header, the document type


declaration follows, commonly referred to as the DOCTYPE −
<!DOCTYPE address [

The DOCTYPE declaration has an exclamation mark (!) at the start of


the element name. The DOCTYPE informs the parser that a DTD is
associated with this XML document.
DTD Body − The DOCTYPE declaration is followed by body of the
DTD, where you declare elements, attributes, entities, and notations.
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>

Several elements are declared here that make up the vocabulary of the
<name> document. <!ELEMENT name (#PCDATA)> defines the
element name to be of type "#PCDATA". Here #PCDATA means parse-
able text data.

End Declaration − Finally, the declaration section of the DTD is closed


using a closing bracket and a closing angle bracket (]>). This effectively
ends the definition, and thereafter, the XML document follows
immediately.
Rules

 The document type declaration must appear at the start of the


document (preceded only by the XML header) − it is not permitted
anywhere else within the document.

 Similar to the DOCTYPE declaration, the element declarations


must start with an exclamation mark.

 The Name in the document type declaration must match the


element type of the root element.

External DTD

In external DTD elements are declared outside the XML file. They are
accessed by specifying the system attributes which may be either the
legal .dtd file or a valid URL. To refer it as external DTD, standalone
attribute in the XML declaration must be set as no. This means,
declaration includes information from the external source.
Syntax

Following is the syntax for external DTD −


<!DOCTYPE root-element SYSTEM "file-name">

where file-name is the file with .dtd extension.


Example

The following example shows external DTD usage −


<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The content of the DTD file address.dtd is as shown −


<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

Types

You can refer to an external DTD by using either system identifiers or


public identifiers.
System Identifiers

A system identifier enables you to specify the location of an external file


containing DTD declarations. Syntax is as follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>

As you can see, it contains keyword SYSTEM and a URI reference


pointing to the location of the document.
Public Identifiers

Public identifiers provide a mechanism to locate DTD resources and is


written as follows −
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address
Example//EN">

As you can see, it begins with keyword PUBLIC, followed by a


specialized identifier. Public identifiers are used to identify an entry in a
catalog. Public identifiers can follow any format, however, a commonly
used format is called Formal Public Identifiers, or FPIs.

XML Schemas
What is an XML Schema?

An XML Schema describes the structure of an XML document.

The XML Schema language is also referred to as XML Schema


Definition (XSD).
XSD Example
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="note">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="to" type="xs:string"/>
      <xs:element name="from" type="xs:string"/>
      <xs:element name="heading" type="xs:string"/>
      <xs:element name="body" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

The purpose of an XML Schema is to define the legal building blocks of


an XML document:

 the elements and attributes that can appear in a document


 the number of (and order of) child elements
 data types for elements and attributes
 default and fixed values for elements and attributes

XSL
XSLT is a language for transforming XML documents.

XPath is a language for navigating in XML documents.

XQuery is a language for querying XML documents.

It Started with XSL

XSL stands for EXtensible Stylesheet Language.

The World Wide Web Consortium (W3C) started to develop XSL


because there was a need for an XML-based Stylesheet Language.

CSS = Style Sheets for HTML

HTML uses predefined tags. The meaning of, and how to display each
tag is well understood.

CSS is used to add styles to HTML elements. 


XSL = Style Sheets for XML

XML does not use predefined tags, and therefore the meaning of each
tag is not well understood.

A <table> element could indicate an HTML table, a piece of furniture,


or something else - and browsers do not know how to display it!

So, XSL describes how the XML elements should be displayed.

XSL - More Than a Style Sheet Language

XSL consists of four parts:


 XSLT - a language for transforming XML documents
 XPath - a language for navigating in XML documents
 XSL-FO - a language for formatting XML documents (discontinued in 2013)
 XQuery - a language for querying XML documents

With the CSS3 Paged Media Module, W3C has delivered a new
standard for document formatting. So, since 2013, CSS3 is proposed as
an XSL-FO replacement.

What is XSLT?

 XSLT stands for XSL Transformations


 XSLT is the most important part of XSL
 XSLT transforms an XML document into another XML document
 XSLT uses XPath to navigate in XML documents
 XSLT is a W3C Recommendation
XSLT = XSL Transformations

XSLT is the most important part of XSL.

XSLT is used to transform an XML document into another XML


document, or another type of document that is recognized by a browser,
like HTML and XHTML. Normally XSLT does this by transforming
each XML element into an (X)HTML element.

With XSLT you can add/remove elements and attributes to or from the
output file. You can also rearrange and sort elements, perform tests and
make decisions about which elements to hide and display, and a lot
more.

A common way to describe the transformation process is to say that


XSLT transforms an XML source-tree into an XML result-tree.

Example :Refer Lab


Program

XML – Processors
When a software program reads an XML document and takes actions
accordingly, this is called processing the XML. Any program that can
read and process XML documents is known as an XML processor. An
XML processor reads the XML file and turns it into in-memory
structures that the rest of the program can access.

The most fundamental XML processor reads an XML document and


converts it into an internal representation for other programs or
subroutines to use. This is called a parser, and it is an important
component of every XML processing program.

Processor involves processing the instructions, that can be studied in the


chapter Processing Instruction.

Types

XML processors are classified as validating or non-validating types,


depending on whether or not they check XML documents for validity. A
processor that discovers a validity error must be able to report it, but
may continue with normal processing.

A few validating parsers are − xml4c (IBM, in C++), xml4j (IBM, in


Java), MSXML (Microsoft, in Java), TclXML (TCL), xmlproc (Python),
XML::Parser (Perl), Java Project X (Sun, in Java).

A few non-validating parsers are − OpenXML (Java), Lark (Java), xp


(Java), AElfred (Java), expat (C), XParse (JavaScript), xmllib (Python).

Web services.
What is Web Service
A Web Service is can be defined by following ways:

 It is a client-server application or application component for


communication.
 The method of communication between two devices over the
network.
 It is a software system for the interoperable machine to machine
communication.
 It is a collection of standards or protocols for exchanging
information between two devices or application.
Let's understand it by the figure given below:

As you can see in the figure, Java, .net, and PHP


applications can communicate with other applications
through web service over the network. For example, the
Java application can interact with Java, .Net, and PHP
applications. So web service is a language independent
way of communication.
Types of Web Services
There are mainly two types of web services.
1. SOAP web services.
2. RESTful web services.

SOAP Web Services


SOAP stands for Simple Object Access Protocol. It is a XML-based
protocol for accessing web services.

SOAP is a W3C recommendation for communication between two


applications.

SOAP is XML based protocol. It is platform independent and language


independent. By using SOAP, you will be able to interact with other
programming language applications.

Advantages of Soap Web Services

WS Security: SOAP defines its own security known as WS Security.

Language and Platform independent: SOAP web services can be


written in any programming language and executed in any platform.

Disadvantages of Soap Web Services

Slow: SOAP uses XML format that must be parsed to be read. It


defines many standards that must be followed while developing the
SOAP applications. So it is slow and consumes more bandwidth and
resource.

WSDL dependent: SOAP uses WSDL and doesn't have any other
mechanism to discover the service.

RESTful Web Services


REST stands for REpresentational State Transfer.

REST is an architectural style not a protocol.


Advantages of RESTful Web Services

Fast: RESTful Web Services are fast because there is no strict


specification like SOAP. It consumes less bandwidth and resource.

Language and Platform independent: RESTful web services can be


written in any programming language and executed in any platform.

Can use SOAP: RESTful web services can use SOAP web services as
the implementation.

Permits different data format: RESTful web service permits different


data format such as Plain Text, HTML, XML and JSON.

You might also like