Friday 19 August 2011

Dynamic HTML(DHTML) tutorial

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.

In this tutorial we will create an application which will create an html element on the fly(i.e. on some event).In this tutorial i am using onmouseover event we can also use onBlur or onclick.

First we will create an html file which is a very basic html file containing some paragraph tags and other elements like textarea and a button. Simply put the name of the javascript function in onmouseover event. your html code should look like this:

#######################HTML#########################script.html
<html>
<head>
<script type="text/javascript" src="script.js" ></script>
</head>
<body>
<h2>Add text to page</h2>
<p><textarea id="textArea" name="textArea"></textarea></p>
<p><input type="button" value="Submit" onmouseover="addNode()" /></p>
</body>
</html>
######################################################

Now we need to create a function in javascipt. In this example function name is addNode().
Create a variable inside the function and put the value of the textArea inside the variable.
Now create a new node by document createTextNode() function and store inside a variable newText.
Use createElement() function to create an HTML element and append the newText on this element(in example the element is the paragraph tag).
Now create a variable docBody and put inside it the body element.
append the previously created elements to docBody using the append child function.
The javascript for the application :

####################JAVASCRIPT####################### script.js
function addNode() {

var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);

var newGraf = document.createElement("p");
newGraf.appendChild(newText);

var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
#######################################################

Now, open the html file in the your browser. Enter some text.On moving mouse over the button you will see new tag being created on each mouseover.


This is the simple Dynamic HTML(DHTML) tutorial.

No comments:

Post a Comment