Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Adding Text to a Page

Next, you can create a script that actually adds text to a page. To do this, you must first create a new text node. This statement creates a new text node with the text "this is a test":

var node=document.createTextNode("this is a test");

Next, you can add this node to the document. To do this, you use the appendChild method. The text can be added to any element that can contain text, but we will use a paragraph. The following statement adds the text node defined previously to the paragraph with the identifier p1:

document.getElementById("p1").appendChild(node);

Listing 14.3 shows the HTML document for a complete example that uses this technique, using a form to allow the user to specify text to add to the page.

Listing 14.3. Adding Text to a Page

<html>
<head>
<title>Adding to a page</title>
<script language="Javascript" type="text/javascript">
function AddText() {
   if (!document.getElementById) return;
   var sentence=document.form1.sentence.value;
   var node=document.createTextNode(" " + sentence);
   document.getElementById("p1").appendChild(node);
   document.form1.sentence.value="";
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p id="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="AddText();">
</form>
</body>
</html>

In this example, the <p> section defines the paragraph that will hold the added text. The <form> section defines a form with a text field called sentence, and an Add button, which calls the AddText() function. This function is defined in the header.

The AddText() function first assigns the sentence variable to the text typed in the text field. Next, it creates a new text node containing the sentence, and appends the new text node to the paragraph.

Load this document into a browser to test it, and try adding several sentences by typing them and clicking the Add button. Figure 14.3 shows Firefox's display of this document after several sentences have been added to the paragraph.

Figure 14.3. Firefox shows the text-adding example.


Try It Yourself

Creating a Navigation Tree

One common use of JavaScript and the DOM is to create a dynamic tree-like navigation system for a site, with sections that can be expanded and collapsed. Although this is unnecessary for small sites, it's a good way to organize what may be hundreds of links for a larger site. To further experiment with the techniques you learned about in this hour, you can create a simple navigation tree using the DOM.

To begin, you will need an HTML document that defines the content of the navigation tree, shown in Listing 14.4.

Listing 14.4. The HTML for the Navigation Tree Example

<html>
<head><title>Creating a Navigation Tree</title>
<style>
   A {text-decoration: none;}
   #productsmenu,#supportmenu,#contactmenu {
     display: none;
     margin-left: 2em;
   }
</style>
</head>
<body>
<h1>Navigation Tree Example</h1>
<p>The navigation tree below allows you to expand and
collapse items.</p>
<ul>
 <li><a id="products" href="#">[+] Products</a>
   <ul ID="productsmenu">
      <li><a href="prodlist.html">Product List</a></li>
      <li><a href="order.html">Order Form</a></li>
      <li><a href="pricelist.html">Price List</a></li>
   </ul>
 </li>
 <li><a id="support" href="#">[+] Support</a>
   <ul id="supportmenu">
      <li><a href="sforum.html">Support Forum</a></li>
      <li><a href="scontact.html">Contact Support</a></li>
   </ul>
 </li>
 <li><a ID="contact" href="#">[+] Contact Us</a>
   <ul id="contactmenu">
    <li><a href="contact1.html">Service Department</a></li>
    <li><a href="contact2.html">Sales Department</a></li>
   </ul>
 </li>
</ul>
<script language="javascript" type="text/javascript"
   src="tree.js">
</script>
</body>
</html>

In this document, the links are laid out as a nested list using <ul> and <li> tags. Using a standard list like this rather than <div> tags has two benefits: First, the browser formats the tree as a list with bullets automatically. Second, it supports older browserseven a browser that does not support CSS or JavaScript will load and display the list correctly. It won't have the dynamic features, but the links will still work.

The tree has three main nodes: Products, Support, and Contact Us. Each one has a link you can click to display or hide the links in that section. The id attribute has been used on each <a> tag so the script can attach an event handler to it. Each node also has a submenu defined with <ul> and <li> tags. An id attribute is also used on the <ul> tag so the script can hide or display the list.

The <script> tag at the end of the document includes the script you will create next. The tag is placed after the body of the page so that the script can add event handlers to elements in the page.

The <style> block at the beginning of the document adds some formatting to the links, and uses the display: none attribute to initially hide the submenus. They will be revealed by the script when the link is clicked.

The script for this example is shown in Listing 14.5.

Listing 14.5. The JavaScript File for the Navigation Tree Example

function Toggle(e) {
   // Don't try this in old browsers
   if (!document.getElementById) return;
   // Get the event object
   if (!e) var e = window.event;
   // Which link was clicked?
   whichlink = (e.target) ? e.target.id : e.srcElement.id;
   // get the menu object
   obj=document.getElementById(whichlink+"menu");
   // Is the menu visible?
   visible=(obj.style.display=="block")
   // Get the key object (the link itself)
   key=document.getElementById(whichlink);
   // Get the name (Products, Contact, etc.)
   keyname = key.firstChild.nodeValue.substring(3);
   if (visible) {
     // hide the menu
     obj.style.display="none";
     key.firstChild.nodeValue = "[+]" + keyname;
   } else {
     // show the menu
     obj.style.display="block";
     key.firstChild.nodeValue = "[-]" + keyname;
   }
}
document.getElementById("products").onclick=Toggle;
document.getElementById("support").onclick=Toggle;
document.getElementById("contact").onclick=Toggle;

The Toggle() function shows or hides a menu. It first determines which of the links triggered the event, and then uses the link's id attribute to find the objects for the menu and for the link itself. If the menu is currently visible, it is hidden, and if it is currently hidden, it is revealed. The appropriate symbol [+] or [-] is added to the link name and displayed by modifying the text node's nodeValue attribute.

The last three lines of the script assign the Toggle() function as the onClick event handler for the three top-level links of the tree.

To use this script, save it as tree.js in the same folder as the HTML document you created previously, and load the HTML file into a browser. Figure 14.4 shows the example in action after all three nodes of the tree have been expanded.

Figure 14.4. The navigation tree example as displayed by Firefox.


Did you Know?

To add items to the navigation tree, add links to the HTML file. If you add a new submenu, you need to assign an id attribute to the link, use the same word plus menu as the id of the menu, and assign its onclick event to the Toggle() function at the end of the script.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Hour 9. Responding to Events
Hour 10. Using Windows and Frames
Hour 11. Getting Data with Forms
Hour 12. Working with Style Sheets
Hour 13. Using the W3C DOM
Hour 14. Using Advanced DOM Features
Working with DOM Nodes
Hiding and Showing Objects
Modifying Text Within a Page
Adding Text to a Page
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele