Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, 6 November 2012

"Use same function by using element ID":Pass id as an argument to use function for different events on different elements


 we can also use a common function that binds to different event associated with different elements and we only pass id and access the function by identifying id in function argument like this


function ValidateForAllValue(id )
{
  var str=""
  $("select#"+id+" option:selected").each(function ( )
  {
    if($(this).val() =="Defined" )
    {
 
     str=str+$(this).val();


    }

    if(str=="Defined" && $(this).val() != "Defined")
    {
 
     alert("Invalid selection: option 'All' can not be selected with any other option");
 
 
        $(".AllClass").val([])
 
      return false;
    }
    if ($(this).val() == "None")
    {
      $(".AllClass").val([]);
 
      alert("Select some valid option");
 
    }
  });
};


Here this function displays alert for the element if  user select "All" along with other option.Therefore we can call this function for any select list by passing on onclick attribute like this:

<select onclick="ValidateForAllValue(this.id)">



Tuesday, 16 October 2012

To write a complete HTML structure in a new window


      function ShowDatePopUp()
        {   
         alert("hello");
         newwindow= window.open('','name','location=1,status=1,scrollbars=1,height=300,width=300');
         newwindow.moveTo(0, 0);
         newwindow.document.write('<html><head><title>');
         newwindow.document.write('Date Window');
         newwindow.document.write('</title></head>');
         newwindow.document.write('<BODY><form>');
      
        newwindow.document.write('<label for='TxtDate'>Enter Date </label>');
        newwindow.document.write('<input type='text' id='DateId' name='TxtDate'/>');

        newwindow.document.write('<input type='submit' value='Submit' class='SubmitButton'/>');
         newwindow.document.write('</form></BODY></html>');
         newwindow.document.close();
        
        
        }
         
         
         
      function ShowDateRangePopUp()
        {{   
         alert("hello");
         newwindow= window.open('','name','location=1,status=1,scrollbars=1,height=300,width=300');
         newwindow.moveTo(0, 0);
         newwindow.document.write('<html><head><title>');
         newwindow.document.write('Date Window');
         newwindow.document.write('</title></head>');
         newwindow.document.write('<BODY><form>');
      
        newwindow.document.write('<label for='TxtDate'>Enter Date </label>');
        newwindow.document.write('<input type='text' id='DateId' name='TxtDate'/>');

        newwindow.document.write('<input type='submit' value='Submit' class='SubmitButton'/>');
         newwindow.document.write('</form></BODY></html>');
         newwindow.document.close();
        
        
        }}

Tuesday, 24 July 2012

Is your hide div is exist in body before you show?

Today I worked on a task in which a hide div has to be display on onclick  event binding.But i was irritated when the div is not showing through show().

Reason: div to be show is not placed in body (because of some if condition or may be it placed in some function that is not called inside body)

Friday, 20 July 2012

Applying validation using Javascript on event binding always use button rather than submit

Reason : Since while checking negative condition on validation  we must restrict the form to load or submit.To stop loading of form  we can't use submit  button because it loads form atleast once

Thursday, 19 July 2012

return false exit from function

We thought return false only stops the form to submit ..but it is not true actually it stops the function to return the value that function wants to return and also exit the program control from the function (Its a programming principle that when a function return false then control exit the function).

Wednesday, 18 July 2012

Calling two function on single event

We can call multiple functions on a single event such as onclick,onsubmit etc by seperating with semicolon sign ;....like this

<a href="..." onclick="fun1();fun2();">

Alert: -1.Make sure the first function not submit the form otherwise second function will not execute and
2. same thing happens when first function have explicit return statement that time also second function may not execute.

Thursday, 5 July 2012

Difference in onclick and onClick()

Event attributes in HTML are not case sensitive, so onclickonClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclicknote that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.

Wednesday, 4 July 2012

Dont write explicitly javascript:Calling a return type js function on event binding


Don't write javascript while returning a function on some event binding.

Ex-<input type="button" value="Submit" onclick="return javascript:ConfirmClientForRelocation()"/>

Here google chrome is not catch this so use instead

Ex-<input type="button" value="Submit" onclick="return ConfirmClientForRelocation()"/>

Saturday, 9 June 2012

email validation function


function emailValidate()
{
alert("hhhhhhhhhhhhhhhhh");

var email = document.getElementById('emailaddressID');

var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
//The test() method tests for a match in a string.
This method returns true if it finds a match, otherwise it returns false
{
alert('Please provide a valid email address');

email.focus();
return false;
}

Thursday, 7 June 2012

DOM "An interesting API to manage web pages" (Theory)


The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.
With the Document Object Model, programmers can build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions - in particular, the DOM interfaces for the XML internal and external subsets have not yet been specified.
As a W3C specification, one important objective for the Document Object Model is to provide a standard programming interface that can be used in a wide variety of environments and applications. The DOM is designed to be used with any programming language. In order to provide a precise, language-independent specification of the DOM interfaces, we have chosen to define the specifications in Object Management Group (OMG) IDL

The name "Document Object Model" was chosen because it is an "object model" in the traditional object oriented design sense: documents are modeled using objects.As an object model, the DOM identifies:
  • the interfaces and objects used to represent and manipulate a document
  • the semantics of these interfaces and objects - including both behavior and attributes
  • the relationships and collaborations among these interfaces and objects



Where the Document Object Model came from

The DOM originated as a specification to allow JavaScript scripts and Java programs to be portable among Web browsers. "Dynamic HTML" was the immediate ancestor of the Document Object Model, and it was originally thought of largely in terms of browsers. However, when the DOM Working Group was formed at W3C, it was also joined by vendors in other domains, including HTML or XML editors and document repositories.



DOM Interfaces and DOM Implementations

The DOM specifies interfaces which may be used to manage XML or HTML documents. It is important to realize that these interfaces are an abstraction - much like "abstract base classes" in C++, they are a means of specifying a way to access and manipulate an application's internal representation of a document. Interfaces do not imply a particular concrete implementation. Each DOM application is free to maintain documents in any convenient representation, as long as the interfaces shown in this specification are supported. Some DOM implementations will be existing programs that use the DOM interfaces to access software written long before the DOM specification existed. Therefore, the DOM is designed to avoid implementation dependencies; in particular,
  1. Attributes defined in the IDL do not imply concrete objects which must have specific data members - in the language bindings, they are translated to a pair of get()/set() functions, not to a data member. Read-only attributes have only a get() function in the language bindings.
  2. DOM applications may provide additional interfaces and objects not found in this specification and still be considered DOM conformant.
  3. Because we specify interfaces and not the actual objects that are to be created, the DOM cannot know what constructors to call for an implementation. In general, DOM users call the createX() methods on the Document class to create document structures, and DOM implementations create their own internal representations of these structures in their implementations of the createX() functions.
The Level 1 interfaces were extended to provide both Level 1 and Level 2 functionality.
DOM implementations in languages other than Java or ECMAScript may choose bindings that are appropriate and natural for their language and run time environment. For example, some systems may need to create a Document2 class which inherits from Document and contains the new methods and attributes.
DOM Level 2 does not specify multithreading mechanisms.



Link:http://www.quirksmode.org/dom/intro.html#change



The Document Object Model (DOM) is the model that describes how all elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself. By calling the element by its proper DOM name, we can influence it.
On this page I give an introduction to the W3C Level 1 DOM that has been implemented in the newest generation of browsers. It will give you an overview of how the DOM works and what you can do with it.
First some words about the DOM Recommendation and the purpose of the DOM, then I teach you what nodes are and how you can walk the DOM tree from node to node. Then it's time to learn how to get a specific node and how to change its value or attributes. Finally, I'll teach you how to create nodes yourself, the ultimate purpose of the new DOM.

The Recommendation

The Level 1 DOM Recommendation has been developed by the W3C to provide any programming language with access to each part of an XML document. As long as you use the methods and properties that are part of the recommendation, it doesn't matter if you parse an XML document with VBScript, Perl or JavaScript. In each language you can read out whatever you like and make changes to the XML document itself.
As some of you might have guessed, this paragraph describes an ideal situation and differences (between browsers, for instance) do exist. Generally, however, they're far smaller than usual so that learning to use the W3C DOM in JavaScript will help you to learn using it in another programming language.
In a way HTML pages can be considered as XML documents. Therefore the Level 1 DOM will work fine on an HTML document, as long as the browser can handle the necessary scripts.
You can read out the text and attributes of every HTML tag in your document, you can delete tags and their content, you can even create new tags and insert them into the document so that you can really rewrite your pages on the fly, without a trip back to the server.
Because it is developed to offer access to and change every aspect of XML documents, the DOM has many possibilities that the average web developer will never need. For instance, you can use it to edit the comments in your HTML document, but I don't see any reason why you would want to do so. Similarly, there are sections of the DOM that deal with the DTD/Doctype, with DocumentFragments (tiny bits of a document) or the enigmatic CDATA. You won't need these parts of the DOM in your HTML pages, so I ignore them and concentrate instead on the things that you'll need in your daily work.

Nodes

The DOM is a Document Object Model, a model of how the various objects of a document are related to each other. In the Level 1 DOM, each object, whatever it may be exactly, is a Node. So if you do
<P>This is a paragraph</P>
you have created two nodes: an element P and a text node with content 'This is a paragraph'. The text node is inside the element, so it is considered a child node of the element. Conversely, the element is considered the parent node of the text node.
              <P> <-- element node
               |
               |
     This is a paragraph <-- text node
If you do
<P>This is a <B>paragraph</B></P>
the element node P has two children, one of which has a child of its own:
              <P>
               |
         --------------
        |              |
    This is a         <B>
                       |
                       |
                    paragraph
Finally there are attribute nodes(Confusingly, they are not counted as children of an element node. In fact, while writing this pages I've done a few tests that seem to indicate that Explorer 5 on Windows doesn't see attributes as nodes at all.) So
<P ALIGN="right">This is a <B>paragraph</B></P>
would give something like
              <P> ----------------
               |                  |
         --------------         ALIGN
        |              |          |
    This is a         <B>         |
                       |        right
                       |
                    paragraph
So these are element nodes, text nodes and attribute nodes. They constitute about 99% of the content of an HTML page and you'll usually busy yourself with manipulating them. There are more kinds of nodes, but I skip them for the moment.
As you'll understand, the element node P also has its own parent, this is usually the document, sometimes another element like a DIV. So the whole HTML document can be seen as a tree consisting of a lot of nodes, most of them having child nodes (and these, too, can have children).
            <BODY>
               |
               |-------------------------------------
               |                                     |
              <P> ----------------            lots more nodes
               |                  |
         --------------         ALIGN
        |              |          |
    This is a         <B>         |
                       |        right
                       |
                    paragraph

Walking through the DOM tree

Knowing the exact structure of the DOM tree, you can walk through it in search of the element you want to influence. For instance, assume the element node P has been stored in the variable x (later on I'll explain how you do this). Then if we want to access the BODY we do
x.parentNode
We take the parent node of x and do something with it. To reach the B node:
x.childNodes[1]
childNodes is an array that contains all children of the node x. Of course numbering starts at zero, so childNodes[0] is the text node 'This is a' andchildNodes[1] is the element node B.
Two special cases: x.firstChild accesses the first child of x (the text node), while x.lastChild accesses the last child of x (the element node B).
So supposing the P is the first child of the body, which in turn is the first child of the document, you can reach the element node B by either of these commands:
document.firstChild.firstChild.lastChild;
document.firstChild.childNodes[0].lastChild;
document.firstChild.childNodes[0].childNodes[1];
etc.
or even (though it's a bit silly)
document.firstChild.childNodes[0].parentNode.firstChild.childNodes[1];

Getting an element

However, walking through the document in this way is quite cumbersome. You'll need to be absolutely certain of the structure of the entire DOM tree and since the whole purpose of the Level 1 DOM is to allow you to modify the DOM tree, this could lead to problems really quickly.
Therefore there are several ways of jumping directly to an element of your choice. Once you have arrived there, you can walk the last bit of the DOM tree to where you want to be.
So let's continue with our example. You want to access the element node B. The very simplest way is to directly jump to it. By the methoddocument.getElementsByTagName you can construct an array of all tags B in the document and then go to one of them. Let's assume that this B is the first one in the document, then you can simply do
var x = document.getElementsByTagName('B')[0]
and x contains the element node B. First you order the browser to get all elements B in the document (document.getElementsByTagName('B')), then you select the first of all B's in the document ([0]) and you've arrived where you want to be.
You could also do
var x = document.getElementsByTagName('P')[0].lastChild;
Now you go to the first paragraph in the document (we assume that our P is the first one) and then go to its lastChild.
The best way, the only way to be certain that you reach the correct element regardless of the current structure of the DOM tree, is to give the B an ID:
<P ALIGN="right">This is a <B ID="hereweare">paragraph</B></P>
Now you can simply say
var x = document.getElementById('hereweare');
and the element node B is stored in x.

Changing a node

Now that we have reached the node, we want to change something. Suppose we want to change the bold text to 'bold bit of text'. We then have to access the correct node and change its nodeValue. Now the correct node in this case is not the element node B but its child text node: we want to change the text, not the element. So we simply do
document.getElementById('hereweare').firstChild.nodeValue='bold bit of text';
and the node changes. Try it and change it back again.
This is a paragraph
You can change the nodeValue of each text node or each attribute. Thus you can also change the ALIGN attribute of the paragraph. Try it and change it back again.
This, too, is quite simple. Take the node you need (the B's parentNode, in this case), then use the setAttribute() method to set the ALIGN attribute to the value you want:
function test2(val) {
 if (document.getElementById && document.createElement)
 {
  node = document.getElementById('hereweare').parentNode;
  node.setAttribute('align',val);
 }
 else alert('Your browser doesn\'t support the Level 1 DOM');
}

Creating and removing nodes

Changing nodes is nice, it can even be useful, but it's nothing compared to actually creating your own nodes and inserting them into your document. I can easily add an HR right below this paragraph andremove it quite as easily.

Creating the element is done by a special method:
var x = document.createElement('HR');
Thus an HR is created and temporarily stored in x. The second step is to insert x into the document. I wrote a special SPAN with ID="inserthrhere" at point where it should appear. So we use theappendChild() method on the SPAN and the HR is made a child of the SPAN and it magically appears:
document.getElementById('inserthrhere').appendChild(x);
Removing it is slightly more complex. First I create a temporary variable node to store the SPAN, then I tell it to remove its first child (the HR).
var node = document.getElementById('inserthrhere')
node.removeChild(node.childNodes[0]);
In the same way we can create a new text node and append it to our faithful B ID="hereweare"
var x = document.createTextNode(' A new text node has been appended!');
document.getElementById('hereweare').appendChild(x);
Try it, then go up to see the result. You will notice that executing the old functions does not remove the new text node, that's because it has become a separate node:
           <B>
            |
       ------------
      |            |
  paragraph    A new text node
               has been appended!
(To merge them into one node use the normalize() method that's sadly not supported by Explorer 5 on Windows).
I won't tell you how to remove the text node, try writing that script yourself. It'll be a useful exercise.



HTML DOM

HTML, the Web's markup language, is specified in terms of the DOM. Layered above the abstract concepts defined in DOM Core, HTML also defines the meaning of elements. The HTML DOM includes such things as the className property on HTML elements, or APIs such as document.body .
The HTML specification also defines restrictions on documents; for example, it requires all children of a ul element, which represents an unordered list, to be lielements, as those represent list items. In general, it also forbids using elements and attributes that aren't defined in a standard.

Other notable APIs

  • The setTimeout and setInterval functions have been first specified on the Window interface in HTML Standard.
  • XMLHttpRequest. API allowing to send asynchronous HTTP request.
  • CSS Object Model. The CSSOM is used to abstract CSS rules as objects
  • WebWorkers. API that allows parallel computation.
  • WebSockets. API that allows low-level bidirectional communication.
  • Canvas 2D Context. Drawing API for the canvas element.

Browser support

Every web developer has experienced that the DOM is a mess. Browser support uniformity varies a lot from feature to feature. The main reason for this situation is the fact that many important DOM features have had very unclear, if any, specifications. Also, different web browsers have added incompatible features for overlapping use cases (like the Internet Explorer event model). The current (as of June 2011) trend is that the W3C and particularly the WHATWG are defining older features in detail, in order to improve interoperability. Following this trend, browsers are improving their implementations based on these specifications.
One common, though perhaps not the most reliable, approach to cross-browser compatibility is to use a JavaScript library. These libraries abstract DOM features and ensure their APIs work similarly in different browsers. Some of the most widely used frameworks are jQueryprototype, and YUI.

Monday, 4 June 2012

DOM Operations with example(Part III)

Link :http://www.ibm.com/developerworks/web/library/wa-jsdom/


In this article, I look at the structure of a Web page from a Document Object Model point of view, examining children and parents and adding nodes to and editing nodes within an existing document. To illustrate this, I build a page where the user can create a series of notes to the page and edit their content. (The page won't get too fancy; I'll leave saving the content, moving them around, resizing them and such to you.) As this is something that could be accomplished without much trouble using DHTML techniques, why bother with DOM?
One of the driving forces behind the development of XML was the fragmentation of HTML, and DHTML follows that trend. Some things have become standard, but a significant divergence in how browsers handle various aspects still exists. DOM is a standard set of interfaces that can be implemented across the board, letting programmers write just one version of their pages.
Besides, Web pages are moving towards XML anyway. XHTML 1.0 is a reformulation of HTML 4.0.1 into XML, and XML is increasingly used to generate Web pages. Ultimately, DOM will be the main technique for accessing the elements and text within these pages. (You can also use it in XSLT style sheets.)
Let's start with the basic page, which includes a work area and form indicating how many notes are already created:

Listing 1. The basic page 
<html>
  <head>
    <title>Getting Sticky</title>
    <style type="text/css">
      * {font-family: sans-serif}
      a {font-size: 6pt}
      .editButton {font-size:6pt}
    </style>

  </head>
  <body>
    <div id="mainDiv" style="height:95%; width:95%; border:3px solid red; 
                                                           padding: 10px;">
    
       <h1>Getting Sticky</h1>

       <form id="noteForm">
           Current number of notes:
                       <input type="text" name="total" value="0" size="3"/>
           <input type="button" value="Add a new note"/>
       </form>

    </div>
  </body>
</html>

Lisitng 1 shows a basic page with a couple of styles (just to pretty it up a little). The body of the page includes a single divelement, which includes a heading element (h1) and a form element. Even in pre-DOM browsers, accessing the information within the form wasn't a problem.

Figure 1. The basic page
The basic page
Using DHTML, you can access the information in a form field, or even change it. For example, you can create a script that increments the current form value by 1, then tell the page to execute the script when the user presses the button:

Listing 2. Incrementing the current number 
<html><head>
    <title>Getting Sticky</title>
    <style type="text/css">
      * {font-family: sans-serif}
      a {font-size: 6pt}
      .editButton {font-size:6pt}
    </style>

    <script type="text/javascript">
      function incrementCurrent() {
        current = parseInt(document.forms["noteForm"].total.value);
        document.forms["noteForm"].total.value = current + 1;
      }
    </script>

  </head><body>
    <div id="mainDiv" style="height:95%; width:95%; border:3px solid red; 
                                                           padding: 10px;">
    
       <h1>Getting Sticky</h1>

       <form id="noteForm">
           Current number of notes:
                      <input type="text" name="total" value="0" size="3"/>
           <input type="button" value="Add a new note" 
                                             onclick="incrementCurrent()"/>
       </form>

    </div>
</body></html>

In Listing 2, the incrementCurrent() function takes the document object, and then pulls the noteForm object out of the array of forms within the page. From the noteForm object, the function gets the form field named total and retrieves the value. It then updates this value within the page.
These kinds of changes are live. If you make the changes to the page, reload, and press the button repeatedly, you'll see that the text field is updated each time.
Similarly, you can retrieve the text of the div element using DHTML properties. Because it has an id of mainDiv, you could use the property innerHTML, as in:
theText = mainDiv.innerHTML;
In this case, you see two DHTML techniques: the forms array, and calling elements by names based on attribute values, rather than by element names or by overall structure. The problem here is that it doesn't lend itself well to generalization. Yes, you can use a variable for the name of the form, but what if an alternate presentation doesn't actually use a form?
If one principle defined the Document Object Model, it would be that information is arranged as a parent-child hierarchy. For example, the following XML:
<parentElement><childElement>My Text Node</childElement></parentElement>
has three nodes: the root node is parentElement. It has one child, the childElement. The childElement element has as its parent the parentElement, and as its child the text node with a value of "My Text Node". The text node has childElement as its parent. Two nodes that share a parent are considered siblings. Notice that the text is its own node. Elements don't actually have a value, they simply have text node children.
You may be familiar with the idea of reading the structure of an XML document using Java technology or another language. When you do so, you use an API, with well-defined functions and object properties. For example, this document has an html element as its root element, which has two children, head and body. (I've removed the white space that would normally appear between these elements to simplify matters; browsers are not yet consistent on how they handle this white space.) To access the bodyelement using Java technology, you could use several different expressions, assuming that you've named the Document objectdocument.
The first approach is to get a list of all of the element's children, then choose a specific item from the list, as in:
bodyElement = document.getChildNodes().item(0).getChildNodes().item(1);
Here, you first get the html element, which is the first child of the document, then get its second child, the body. (getChildNodes() is zero-based.) An alternative approach is to access the html element as first child directly, then move to its first child (head), and then to that element's next sibling (the second child, body):
bodyElement = document.getFirstChild().getFirstChild().getNextSibling();
From there you can get the type of node:
typeInt = bodyElement.getNodeType()
Node types are returned as integers, and allow you to handle each node appropriately; an element (type 1) has a name, but no value, whereas a text node (type 3) has a value but no name.
Once you know what you have, you can retrieve the name of the element:
elementName = bodyElement.getNodeName();
or its text contents:
elementContent = bodyElement.getFirstChild().getNodeValue();
(Remember, the text of an element is a node unto itself, with the element as its parent.)
When you move these functions over to JavaScript, the same basic API is in place, but it's handled slightly differently. For example, properties are accessed directly, rather than through get and set methods, so the same statements in JavaScript would be represented as
bodyElement = document.childNodes.item(0).childNodes.item(1);
bodyElement = document.firstChild.firstChild.nextSibling;
From there you can get the type and name of the element, as well as its contents:
ElementType = bodyElement.nodeType;
elementName = bodyElement.nodeName;
elementContent = bodyElement.firstChild.nodeValue;
Be aware, however, that only properties undergo this name change. Functions that return objects remain constant. For example, you can retrieve a specific object based on its ID, as in:
formElement = document.getElementById("noteForm");
That's the basic idea. Let's see it in action.
The actual note itself is just a small box with standard text and a link that enables the user to edit the text later, as seen in Figure 2.

Figure 2. The new note
The new note
This is the equivalent of the following HTML:

Listing 3. The target HTML
<div id="note1" style="width: 100; height:100; border: 1px solid blue; 
                       background-color: yellow; position: absolute; 
                       top: 150; left: 135">
    <a href="javascript:editNote('note1')">edit</a>
    <br />
    New note
</div>

Adding the actual element uses standard DOM techniques, as seen in Listing 4:

Listing 4. Adding the new note element
<html>
  <head>
    <title>Getting Sticky</title>
    <style type="text/css">
      * {font-family: sans-serif}
      a {font-size: 6pt}
      .editButton {font-size:6pt}
    </style>

    <script type="text/javascript">
...
      function getCurrentNumber() {
        formElement = document.getElementById("noteForm");
        return formElement.childNodes.item(1).value;
      }

      function makeNewNote(){
        mainDivElement = document.getElementById("mainDiv");

        newNote = document.createElement("div");
        newNote.setAttribute("id", "note"+getCurrentNumber());

        mainDivElement.appendChild(newNote);

        incrementCurrent();

      }
    </script>
  </head>
  <body>
    <div id="mainDiv" style="height:85%; width:85%; border:3px solid red; 
                                             padding: 10px; z-index: -100" >
    
       <h1>Getting Sticky</h1>

       <form id="noteForm">
           Current number of notes  <input type="text" name="total" value="0" 
                                             size="3"/>
           <input type="button" value="Add a new note" 
                                             onclick="makeNewNote()"/>
       </form>

    </div>
  </body>
</html>

In this case, you've changed the button so that it causes the execution of makeNewNote() rather than incrementCurrent(), though that function is still in use within makeNewNote(). First, you use getElementById() to get a reference to the main divelement that ultimately will contain the note. You then use the document object to create a new element, just as you would do in any other language, with the name of div. To set the id attribute, you simply use the setAttribute() method on the new element.
Each note will have a unique id attribute, so you need to know what the current total is. To get this information, you start at the level of the form element itself. From there, you retrieve the list of children. The first (with an index of 0) is the text, and the second (with an index of 1) is the actual input element.
But what about .value? Isn't that a typo? Shouldn't it be nodeValue?
Actually, no. Remember, elements don't have values. At first glance, it might look as though I'm mixing DOM and DHTML properties, but in actuality, the element retrieved here is not just an implementation of org.w3c.dom.Element, it's an implementation of org.w3c.dom.html.HTMLInputElement, which also includes a value property that represents the value of the form field. In this way, DOM mimics some (though not all) of the properties that were available through DHTML.
Once the attribute is set, you simply append the new div element to the mainDiv element, where it will appear. Or at least, it would if it had any presentation properties or text.
To add the style information, you will actually use the DHTML style object:

Listing 5. Adding style information
...
      function makeNewNote(){
        mainDivElement = document.getElementById("mainDiv");

        newNote = document.createElement("div");
        newNote.setAttribute("id", "note"+getCurrentNumber());

        newNote.style.width="100";
        newNote.style.height="100";
        newNote.style.border="1px solid blue";
        newNote.style.backgroundColor="yellow";
        newNote.style.position="absolute";
        newNote.style.top=(150);
        newNote.style.left=(25 + 110*getCurrentNumber());

        mainDivElement.appendChild(newNote);

        incrementCurrent();

      }
...

The result is a small yellow box with a blue border, as shown in Figure 3.

Figure 3. The empty box
The empty box
Notice that the left property of the note depends on the current number of notes, which increments after each note is added. This way, you can add a series of boxes, as shown in Figure 3.
Adding the content of the div presents a bit of a problem. I could use the innerHTML property:

newNote.innerHTML = "<a href=\"javascript:editNote('note"  
                     +getCurrentNumber()+")\">edit</a><br />New note";

but how could I do it using straight DOM methods? The first thought would be to simply set the value of the text node child of thediv element:

noteText = document.createTextNode(
          "<a href=\"javascript:editNote('note"+getCurrentNumber()+")\">"+
          "edit</a><br />New note");
newNote.appendChild(noteText);

The text does indeed get added, but the results might not quite be what you expect, as shown in Figure 4.

Figure 4. The text in the box
The text in the box
The problem is that you're not really adding text, but rather mixed content, consisting of text and elements. The browser assumes that you mean this as CDATA, which is taken literally, and the elements are not created. Rather than simply adding all of the content in one block, you need to actually add each element:

Listing 6. Adding the content
...
  function makeNewNote(){
    mainDivElement = document.getElementById("mainDiv");

    newNote = document.createElement("div");
    newNote.setAttribute("id", "note"+getCurrentNumber());
...

      editLink = getEditLink("note"+getCurrentNumber());
      newNote.appendChild(editLink);
      newNote.appendChild(document.createElement("br"));
 
      noteText = document.createTextNode("New Form");
      newNote.appendChild(noteText);

    mainDivElement.appendChild(newNote);

    incrementCurrent();

  }

    function getEditLink(thisId){
      editLink = document.createElement("a");
      linkText = document.createTextNode("edit");

      editLink.setAttribute("href", "javascript:editNote('"+thisId+"')");
        
      editLink.appendChild(linkText);
      return editLink;
    }
...

First, you've created a new function, getEditLink, which returns an object. That object is the a element, which you created using standard DOM methods. Next, you add a standard break tag, br, and finally, the node that contains the actual note text.
The result is the completed note, with elements intact and ready for use.
Now you have the content, but how can you change it? Because you added elements separately, you can just edit the single text node that represents the text of the note. You can do this three ways. First, you can remove the offending node and add a new one:

Listing 7. Removing the node and adding a replacement
...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        oldNode = theDiv.firstChild.nextSibling.nextSibling;
        theDiv.removeChild(oldNode);

        newNode = document.createTextNode(newText);
        theDiv.appendChild(newNode);

      }
...

Another option is to simply replace the existing node:

Listing 8. Replacing a node
...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        oldNode = theDiv.firstChild.nextSibling.nextSibling;
        newNode = document.createTextNode(newText);
        theDiv.replaceChild(newNode, oldNode);
      }
...

In this case, the oldNode is replaced with the newNode, and the document changes accordingly.
Finally, you could simply change the text of the existing node:

Listing 9. Changing the existing node
...
      function editNote(editLink){
        theDiv = document.getElementById(editLink);
        newText = prompt("What should the note say?");

        theDiv.firstChild.nextSibling.nextSibling.nodeValue=newText;
      }
...

Because editNote takes the id value of the appropriate div, the same function can be used for any note, as seen in Figure 5.

Figure 5. The final page
The final page
In this article, you've taken a very basic look at the use of DOM in the JavaScript of a Web page. You can use the same principles anywhere JavaScript is in use, such as within an XSLT style sheet.
The Document Object Model represents elements, text, and other types of nodes within an XML document as a series of parent-child relationships. By manipulating these individual nodes, you can affect the page itself. In addition to DOM Core methods, an XHTML page can also expose properties and methods that are part of the DOM HTML module, which attempts to integrate many of the DHTML properties that programmers have been using for years.