dhtml and dom

13
DHTML is NOT a language. DHTML is a TERM describing the art of making dynamic and interactive web pages. DHTML combines HTML, JavaScript, the HTML DOM, and CSS. Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated web sites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model. DHTML combines HTML with cascading Style Sheet (CSS) and Scripting Languages. HTML specifies a webpage’s elements like table, frame paragraph, bulleted list etc. Cascading Style Sheets can be used to determine an element’s size, color, position and a number of other features. Scripting Languages (JavaScript and VBscript) can be used to manipulate the web page’s elements so that styles assigned to them can change in response to a user’s input. DHTML allows scripting languages to change variables in a web page's definition language, which in turn affects the look and function of otherwise "static" HTML page content, after the page has been fully loaded and during the viewing process. Thus the dynamic characteristic of DHTML is the way it functions while a page is viewed, not in its ability to generate a unique page with each page load. By contrast, a dynamic web page is a broader concept — any web page generated differently for each user, load occurrence, or specific variable values. This includes pages created by client-side scripting, and ones created by server- side scripting (such as PHP, Perl, JSP or ASP.NET) where the web server generates content before sending it to the client. JavaScript JavaScript is the most popular scripting language on the internet, and it works in all major browsers. DHTML is about using JavaScript to control access and manipulate HTML elements. HTML DOM The HTML DOM is a W3C standard. It describes the Document Object Model for HTML. The HTML DOM defines a standard way for accessing and manipulating HTML documents. DHTML is about using the DOM to access and manipulate HTML elements. HTML Events HTML events are a part of the HTML DOM. DHTML is about creating web pages that reacts to (user) events. CSS CSS defines how to display HTML elements. DHTML is about using JavaScript and the HTML DOM to change the style and positioning of HTML elements. What is the use of DHTML? DHTML allows authors to add effects to their pages that are otherwise difficult to achieve. For example, DHTML allows the page author to: * Animate text and images in their document, independently moving each element from any starting point to any ending point, following a predetermined path or one chosen by the user. * Embed a ticker that automatically refreshes its content with the latest news, stock quotes, or other data. * Use a form to capture user input, and then process and respond to that data without having to send data back to the server. * Include rollover buttons or drop-down menus. Document Object Model (DOM) JAVA, C++ Languages are said to be object oriented programming language bcoz they incorporate object that are used for providing much of programming functionality. (The actual work of a program is done by methods and properties of the various objects.) JavaScript is not a true object oriented programming language, although it does include many characteristics commonly associated with object oriented languages. One common characteristic of object oriented programming is inheritance, in which an object derived from another object inherits the methods and properties of the object from which it descends. Collection of objects that descend from one another are referred to as object models. In JavaScript and HTML the concept of inheritance and object model is important. In object model the objects are derived from one common top-level ancestor object.

Upload: jagannath-swain

Post on 12-Jul-2015

197 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Dhtml and dom

DHTML is NOT a language. DHTML is a TERM describing the art of making dynamic and interactive web pages. DHTML combines HTML, JavaScript, the HTML DOM, and CSS. Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated web sites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model.DHTML combines HTML with cascading Style Sheet (CSS) and Scripting Languages. HTML specifies a webpage’s elements like table, frame paragraph, bulleted list etc. Cascading Style Sheets can be used to determine an element’s size, color, position and a number of other features. Scripting Languages (JavaScript and VBscript) can be used to manipulate the web page’s elements so that styles assigned to them can change in response to a user’s input.DHTML allows scripting languages to change variables in a web page's definition language, which in turn affects the look and function of otherwise "static" HTML page content, after the page has been fully loaded and during the viewing process. Thus the dynamic characteristic of DHTML is the way it functions while a page is viewed, not in its ability to generate a unique page with each page load.By contrast, a dynamic web page is a broader concept — any web page generated differently for each user, load occurrence, or specific variable values. This includes pages created by client-side scripting, and ones created by server-side scripting (such as PHP, Perl, JSP or ASP.NET) where the web server generates content before sending it to the client.

JavaScriptJavaScript is the most popular scripting language on the internet, and it works in all major browsers. DHTML is about using JavaScript to control access and manipulate HTML elements.

HTML DOMThe HTML DOM is a W3C standard. It describes the Document Object Model for HTML. The HTML DOM defines a standard way for accessing and manipulating HTML documents. DHTML is about using the DOM to access and manipulate HTML elements.

HTML EventsHTML events are a part of the HTML DOM. DHTML is about creating web pages that reacts to (user) events.

CSSCSS defines how to display HTML elements. DHTML is about using JavaScript and the HTML DOM to change the style and positioning of HTML elements.What is the use of DHTML?DHTML allows authors to add effects to their pages that are otherwise difficult to achieve. For example, DHTML allows the page author to:

* Animate text and images in their document, independently moving each element from any starting point to any ending point, following a predetermined path or one chosen by the user.

* Embed a ticker that automatically refreshes its content with the latest news, stock quotes, or other data. * Use a form to capture user input, and then process and respond to that data without having to send data back

to the server. * Include rollover buttons or drop-down menus.

Document Object Model (DOM)JAVA, C++ Languages are said to be object oriented programming language bcoz they incorporate object that are used for providing much of programming functionality. (The actual work of a program is done by methods and properties of the various objects.) JavaScript is not a true object oriented programming language, although it does include many characteristics commonly associated with object oriented languages. One common characteristic of object oriented programming is inheritance, in which an object derived from another object inherits the methods and properties of the object from which it descends. Collection of objects that descend from one another are referred to as object models.In JavaScript and HTML the concept of inheritance and object model is important. In object model the objects are derived from one common top-level ancestor object.

Page 2: Dhtml and dom

The core of the DHTML is the Document object model. Within a DHTML page the Document object model or DOM represents the web page displayed in a window. Each HTML element on a Web page is represented in the DOM by its own object with various events, properties and methods. At the top of the DOM hierarchy is the Document object.Whenever you have used images and forms or have referred to the Document object, you have used DOM. You have used 2 methods of the document object, write() and writeln() extensively. The document object refers not only to HTML document, but also to other file types that are displayed in a web browser such as .jpg, .gif .xml etc.

What is the Document Object Model?The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page. The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use. The public interface of a DOM is specified in its application programming interface (API).Following figure shows how objects are derived from each other.Document

Form Text-areaApplet TextAnchor File-uploadArea PasswordImage HiddenLink Submit

Reset Radio Checkbox Button Select Option

There are 3 Levels or parts of DOM exists:• The Core DOM - standard model for any structured document.• The HTML DOM - standard model for HTML documents.• The XML DOM - standard model for XML documents.

HTML DOMThe HTML DOM is:

• A standard object model for HTML• A standard programming interface for HTML• Platform- and language-independent• A W3C standard

The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. According to DOM everything in an HTML Document is a node. It states that :

The entire document is a document node. Every HTML element is an element node. The texts in the HTML element are text nodes. Every HTML attribute is an attribute node. Comments are comment nodes.

The DOM presents an HTML document as a tree-structure. All nodes can be accessed through the tree. Their contents can be modified are deleted and new elements can be created.

Page 3: Dhtml and dom

HTML DOM Tree:

The nodes can be accessed with JavaScript or other programming languages. The programming interface of the DOM is defined by standard properties and methods.

Properties are often referred to as something that is.(e.g. the name of a node). Methods are often referred to as something that is done (e.g. remove a node).

Example:<html> <head> <title>DOM </title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body></html>The root node in the HTML above is <html>. All other nodes in the document are contained within <html>. The <html> node has two child nodes; <head> and <body>. The <head> node holds a <title> node. The <body> node holds a <h1> and <p> node.Text is Always Stored in Text Nodes:A common error in DOM processing is to expect an element node to contain text. However, the text of an element node is stored in a text node. In this example: <title>DOM l</title>, the element node <title>, holds a text node with the value "DOM"."DOM" is not the value of the <title> element. However, in the HTML DOM the value of the text node can be accessed by the inner-HTML property.The terms parent, child, and sibling are used to describe the relationships. Parent nodes have children. Children on the same level are called siblings (brothers or sisters).The following image illustrates a part of the node tree and the relationship between the nodes:

Page 4: Dhtml and dom

From the HTML above: The <html> node has no parent node; it is the root node The parent node of the <head> and <body> nodes is the <html> node The parent node of the "Hello world!" text node is the <p> node

and: The <html> node has two child nodes; <head> and <body> The <head> node has one child node; the <title> node The <title> node also has one child node; the text node "DOM Tutorial" The <h1> and <p> nodes are siblings, and both child nodes of <body>

First Child - Last ChildFrom the HTML above:

The <head> element is the first child of the <html> element, and the <body> element is the last child of the <html> element

The <h1> element is the first child of the <body> element, and the <p> element is the last child of the <body> element

HTML DOM PropertiesX represents x is a node object (HTML element).Some DOM properties:

• x.innerHTML - the text value of x• x.nodeName - the name of x• x.nodeValue - the value of x• x.parentNode - the parent node of x• x.childNodes - the child nodes of x• x.attributes - the attributes nodes of x

HTML DOM MethodsSome DOM methods:

• x.getElementById(id) - get the element with a specified id• x.getElementsByTagName(name) - get all elements with a specified tag name• x.appendChild(node) - insert a child node to x• x.removeChild(node) - remove a child node from x

The Inner-HTML Property-The easiest way to get or modify the content of an element is by using the inner-HTML property. Inner-HTML is not a part of the W3C DOM specification. However, it is supported by all major browsers. The inner-HTML property is useful for returning or replacing the content of HTML elements (including <html> and <body>), it can also be used to view the source of a page that has been dynamically modified.Example:-The following code gets the inner-HTML (text) from the <p> element with id="intro":<html><body><p id="intro">Hello World!</p><script type="text/javascript">txt=document.getElementById("intro").innerHTML;document.write("<p>The text from the intro paragraph: " + txt + "</p>");</script></body></html>In the example above, getElementById is a method, while inner-HTML is a property.Output: Hello World!The text from the intro paragraph: Hello World!

Page 5: Dhtml and dom

childNodes and nodeValueWe can also use the childNodes and nodeValue properties to get the content of an element.The following code gets the value of the <p> element with id="intro":Example:<html><body><p id="intro">Hello World!</p><script type="text/javascript">txt=document.getElementById("intro").childNodes[0].nodeValue;document.write("<p>The text from the intro paragraph: " + txt + "</p>");</script></body></html>In the example above, getElementById is a method, while childNodes and nodeValue are properties.output same as that of above example.

Accessing Nodes:-With the DOM, you can access every node in an HTML document.You can access a node in three ways:

• By using the getElementById() method• By using the getElementsByTagName() method• By navigating the node tree, using the node relationships

The getElementById() Method:The getElementById() method returns the element with the specified ID:Syntax:node.getElementById("id");

The following example gets the element with id="intro":<html><body><p id="intro">Hello World!</p><p>This example demonstrates the <b>getElementById</b> method!</p><script type="text/javascript">x=document.getElementById("intro");document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");</script></body></html>

The getElementsByTagName() Method:getElementsByTagName() returns all elements with a specified tag name.Syntaxnode.getElementsByTagName("tagname");

The following example returns a nodeList of all <p> elements in the document:<html><body><p>Hello World!</p><div id="main"><p>The DOM is very useful.</p><p>This example demonstrates the <b>getElementsByTagName</b> method</p></div>

Page 6: Dhtml and dom

<script type="text/javascript">x=document.getElementById("main").getElementsByTagName("p");document.write("First paragraph inside the div: " + x[0].innerHTML);</script></body></html>Output:Hello World!The DOM is very useful.This example demonstrates the getElementsByTagName methodFirst paragraph inside the div: The DOM is very useful.

DOM Node ListThe getElementsByTagName() method returns a node-list. A node-list is an array of nodes.The following code selects all <p> nodes in a node-list:

x=document.getElementsByTagName("p");

The nodes can be accessed by index number. To access the second <p> you can write:y=x[1];

Note: The index starts at 0.Example:<html><body><p>Hello World!</p><p>The DOM is very useful!</p><script type="text/javascript">x=document.getElementsByTagName("p");document.write("Text of second paragraph: " + x[1].innerHTML);</script></body></html>

DOM Node List LengthThe length property defines the number of nodes in a node-list.You can loop through a node-list by using the length property:

<html><body><p>Hello World!</p><p>The DOM is very useful!</p><p>This example demonstrates the <b>length</b> property.</p><script type="text/javascript">x=document.getElementsByTagName("p");for (i=0;i<x.length;i++) { document.write(x[i].innerHTML); document.write("<br />"); }</script></body></html>

Page 7: Dhtml and dom

Output:Hello World!

The DOM is very useful!

This example demonstrates the length property.Hello World!The DOM is very useful!This example demonstrates the length property.

Explaination:

1. Get all <p> element nodes2. For each <p> element, output the value of its text node

Navigating Node Relationships

The three properties; parentNode, firstChild, and lastChild, follow the document structure and allow short-distance travel in a document.

Look at the following HTML fragment:<html><body><p>Hello World!</p><div> <p>The DOM is very useful!</p> <p>This example demonstrates node relationships.</p></div></body></html>

In the HTML code above, the first p element is the first child node (firstChild) of the body element, and the div element is the last child node (lastChild) of the body element. The parent node (parentNode) of the first p element and the div element, is the the body element, and the parent node of the p elements inside the div element, is the div element.The firstChild property can also be used to access the text of an element:Example:<html><body><p id="intro">Hello World!</p><script type="text/javascript">x=document.getElementById("intro");document.write(x.firstChild.nodeValue);</script></body></html>

DOM Root NodesThere are two special document properties that allow access to the tags:

* document.documentElement - returns the root node of the document

Page 8: Dhtml and dom

* document.body - gives direct access to the <body> tag

HTML DOM Node Information

The nodeName, nodeValue, and nodeType properties contain information about nodes.Node Properties:In the HTML DOM, each node is an object.Objects have methods and properties that can be accessed and manipulated by JavaScript.Three important node properties are: * nodeName * nodeValue * nodeType

The nodeName PropertyThe nodeName property specifies the name of a node.

* nodeName is read-only * nodeName of an element node is the same as the tag name * nodeName of an attribute node is the attribute name * nodeName of a text node is always #text * nodeName of the document node is always #document

Note: nodeName always contains the uppercase tag name of an HTML element.

The nodeValue PropertyThe nodeValue property specifies the value of a node.

* nodeValue for element nodes is undefined * nodeValue for text nodes is the text itself * nodeValue for attribute nodes is the attribute value

Get the Value of an ElementThe following example retrieves the text node value of the <p id="intro"> tag:

Example:<html><body><p id="intro">Hello World!</p><script type="text/javascript">x=document.getElementById("intro");document.write(x.firstChild.nodeValue);</script></body></html>Output:Hello World!Hello World!

The nodeType Property

The nodeType property returns the type of node. nodeType is read only.

Page 9: Dhtml and dom

The most important node types are:

Element type NodeType

Element 1

Attribute 2

Text 3

Comment 8

Document 9

HTML DOM - Change HTML Elements

1.HTML elements can be changed using JavaScript, the HTML DOM and events. HTML DOM and JavaScript can change the inner content and attributes of HTML elements.

The following example changes the background color of the <body> element:<html><body><script type="text/javascript">document.body.bgColor="lavender";</script></body></html>The above code changes the background color.

2. Change the Text of an HTML Element – inner-HTMLThe easiest way to get or modify the content of an element is by using the inner-HTML property.

The following example changes the text of a <p> element:<html><body><p id="p1">Hello World!</p><script type="text/javascript">document.getElementById("p1").innerHTML="New text!";</script></body></html>3. Change an HTML Element Using EventsAn event handler allows you to execute code when an event occurs. Events are generated by the browser when the user clicks an element, when the page loads, when a form is submitted, etc. You can read more about events in the next chapter.The following example changes the background color of the <body> element when a button is clicked:<html><body><input type="button" onclick="document.body.bgColor='red';"value="Change background color" /></body></html> The above code changes the background color to red onclick.4. Change the Text of an Element - with a Function:The following example uses a function to change the text of the <p> element when a button is clicked:

Page 10: Dhtml and dom

<html><head><script type="text/javascript">function ChangeText(){document.getElementById("p1").innerHTML="New text!";}</script></head><body><p id="p1">Hello world!</p><input type="button" onclick="ChangeText()" value="Change text" /></body></html>

5. Using the Style Object:The Style object of each HTML element represents its individual style.The following example uses a function to change the style of the <body> element when a button is clicked:<html><head><script type="text/javascript">function ChangeBackground(){document.body.style.backgroundColor="lavender";}</script></head><body><input type="button" onclick="ChangeBackground()"value="Change background color" /></body></html>

6. Change the font and color of an ElementThe following example uses a function to change the style of the <p> element when a button is clicked:<html><head><script type="text/javascript">function ChangeStyle(){document.getElementById("p1").style.color="blue";document.getElementById("p1").style.fontFamily="Arial";}</script></head><body><p id="p1">Hello world!</p><input type="button" onclick="ChangeStyle()" value="Change style" /> </body></html>

Page 11: Dhtml and dom

HTML DOM - Events Events:Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML elements.

Examples of events: * A mouse click * A web page or an image loading * Mouse over a hot spot on the web page * Selecting an input box in an HTML form * Submitting an HTML form * A keystrokeNote: Events are normally used in combination with functions, and the function will not be executed before the event occurs.

Event ObjectEvents are actions that can be detected by JavaScript, and the event object gives information about the event that has occurred. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. Events are normally used in combination with functions, and the function will not be executed before the event occurs!

Event Attributes

E: Internet Explorer, F: Firefox, O: Opera, W3C: W3C Standard.

Attribute The event occurs when... IE F O W3C

onblur An element loses focus 3 1 9 Yes

onchange The content of a field changes 3 1 9 Yes

onclick Mouse clicks an object 3 1 9 Yes

ondblclick Mouse double-clicks an object 4 1 9 Yes

onerror An error occurs when loading a document or an image 4 1 9 Yes

onfocus An element gets focus 3 1 9 Yes

onkeydown A keyboard key is pressed 3 1 No Yes

onkeypress A keyboard key is pressed or held down 3 1 9 Yes

onkeyup A keyboard key is released 3 1 9 Yes

onload A page or image is finished loading 3 1 9 Yes

onmousedown A mouse button is pressed 4 1 9 Yes

onmousemove The mouse is moved 3 1 9 Yes

Page 12: Dhtml and dom

onmouseout The mouse is moved off an element 4 1 9 Yes

onmouseover The mouse is moved over an element 3 1 9 Yes

onmouseup A mouse button is released 4 1 9 Yes

onresize A window or frame is resized 4 1 9 Yes

onselect Text is selected 3 1 9 Yes

onunload The user exits the page 3 1 9 Yes

Mouse / Keyboard AttributesProperty Description IE F O W3C

altKeyReturns whether or not the "ALT" key was pressed when an event was triggered

6 1 9 Yes

buttonReturns which mouse button was clicked when an event was triggered

6 1 9 Yes

clientXReturns the horizontal coordinate of the mouse pointer when an event was triggered

6 1 9 Yes

clientYReturns the vertical coordinate of the mouse pointer when an event was triggered

6 1 9 Yes

ctrlKeyReturns whether or not the "CTRL" key was pressed when an event was triggered

6 1 9 Yes

metaKeyReturns whether or not the "meta" key was pressed when an event was triggered

6 1 9 Yes

relatedTargetReturns the element related to the element that triggered the event

No 1 9 Yes

screenXReturns the horizontal coordinate of the mouse pointer when an event was triggered

6 1 9 Yes

screenYReturns the vertical coordinate of the mouse pointer when an event was triggered

6 1 9 Yes

shiftKeyReturns whether or not the "SHIFT" key was pressed when an event was triggered

6 1 9 Yes

Other Event AttributesProperty Description IE F O W3C

Page 13: Dhtml and dom

bubblesReturns a Boolean value that indicates whether or not an event is a bubbling event

No 1 9 Yes

cancelableReturns a Boolean value that indicates whether or not an event can have its default action prevented

No 1 9 Yes

currentTarget Returns the element whose event listeners triggered the event No 1 9 Yes

eventPhaseReturns which phase of the event flow is currently being evaluated

Yes

target Returns the element that triggered the event No 1 9 Yes

timeStampReturns the time stamp, in milliseconds, from the epoch (system start or event trigger)

No 1 9 Yes

type Returns the name of the event 6 1 9 Yes

Some examples of event objects:

onload and onUnloadThe onload and onUnload events are triggered when the user enters or leaves a page.The onload event is often used to check the visitor's browser type and version, and load the proper version of the web page based on that information.Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

onFocus, onBlur and onChangeThe onFocus, onBlur and onChange events are often used in combination with validation of form fields.Below is an example of how to use an onChange event. The checkEmail() function will be called whenever the user changes the content of the e-mail field:<E-mail: <input type="text" id="email" onchange="checkEmail()" />