Nice book written by Christian Heilmann.I really liked the javascript pagination example.We can surely come to conclusion that author is a geek.
Few points i want to share from the book.
1) Netscape created the JavaScript language in 1996 and included it in their Netscape Navigator (NN) 2.0 browser via an interpreter that read and executed the JavaScript added to .html pages
2) The merits of using JavaScript are
a) Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means saving money.
b) Immediate feedback to the visitors: They don’t have to wait for a page reload to see if they have forgotten to enter something
c) Automated fixing of minor errors: For example, if you have a database system that expects a date in the format dd-mm-yyyy and the visitor enters it in the form dd/mm/yyyy,a clever JavaScript script could change this minor mistake prior to sending the form to the server. If that was the only mistake the visitor made, you can save her an error message—thus making it less frustrating to use the site.
d)Increased usability by allowing visitors to change and interact with the user interface without reloading the page: For example, by collapsing and expanding sections of the page or offering extra options for visitors with JavaScript. A classic example of this would be select boxes that allow immediate filtering, such as only showing the available destinations for a certain airport, without making you reload the page and wait for the result.
e)Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. This is partly possible with CSS and HTML as well, but JavaScript offers you a lot wider—and more widely supported—range of options.
f) Richer interfaces: If your users allow for it, you can use JavaScript to include such items as drag-and-drop components and sliders—something that originally was only possible in thick client applications your users had to install, such as Java applets or browser plug-ins like Flash.
g) Lightweight environment: Instead of downloading a large file like a Java applet or a Flash movie, scripts are small in file size and get cached (held in memory) once they have been loaded. JavaScript also uses the browser controls for functionality rather than its own user interfaces like Flash or Java applets do. This makes it easier for users, as they already know these controls and how to use them. Modern Flash and Macromedia Flex applications do have the option to stream media and—being vector based—are visually scalable, something JavaScript and HTML controls aren’t. On the other hand, they require the plug-in to be installed.
3) Rounding Numbers
We saw earlier that the parseInt() function will make a fractional number whole by removing everything after the decimal point (so 24.999 becomes 24). Pretty often you’ll want more mathematically accurate calculations, if you’re working with financial calculations, for example,and for these you can use one of the Math object’s three rounding functions: round(), ceil(),and floor().
This is how they work:
• round(): Rounds a number up when the decimal is . 5 or greater
• ceil() (as in ceiling): Always rounds up, so 23.75 becomes 24, as does 23.25
• floor(): Always rounds down, so 23.75 becomes 23, as does 23.25
4) Joining Two Arrays
The Array object’s concat() method allows us to concatenate arrays. We can add two or more arrays using this method, each new array starting where the previous one ends. Here we’re joining three arrays: arrayOne, arrayTwo, and arrayThree:
<html>
<body>
<script type="text/javascript">
var arrayOne = new Array( "One", "Two", "Three",➥
"Four", "Five" );
var arrayTwo = new Array( "ABC", "DEF", "GHI" );
var arrayThree = new Array( "John", "Paul", "George",➥
"Ringo" );
var joinedArray = arrayOne.concat( arrayTwo, arrayThree );
document.write( "joinedArray has " + joinedArray.length + ➥
" elements<br>" );
document.write( joinedArray[0] + "<br>" )
document.write( joinedArray[11] + "<br>" )
</script>
</body>
</html>
5) Below Code will try to add new html anchor element by javascript.
<html>
<head>
<script>
function createLink(linkTarget,linkName){
if (linkTarget == null) { linkTarget = '#'; }
if (linkName == null) { linkName = 'dummy'; }
var tempLink=document.createElement('a');
tempLink.setAttribute('href',linkTarget);
tempLink.appendChild(document.createTextNode(linkName));
document.getElementById('linkTest').appendChild(tempLink);
return tempLink;
}
</script>
</head>
<body id="linkTest" onLoad="createLink('temp','templink')">
</body>
</html>
6) Every node in the document has several valuable properties.
a) The most important is nodeType, which describes what the node is—an element, an attribute, a comment, text, and several more types (12 in all). For our HTML examples,only the nodeType values 1 and 3 are important, where 1 is an element node and 3 is a text node.
b) Another important property is nodeName, which is the name of the element or #text if it is a text node. Depending on the document type and the user agent, nodeName can be either upper- or lowercase, which is why it is a good idea to convert it to lowercase before testing for a certain name. You can use the toLowerCase() method of the string object for that: if(obj.nodeName.toLowerCase()=='li'){};. For element nodes, you can use the tagName property.
c) nodeValue is the value of the node: null if it is an element, and the text content if it is a text node.
7) Creating, Removing, and Replacing Elements
DOM also provides methods for changing the structure of the document you can use in an HTML/JavaScript environment (there are more if you do XML conversion via JavaScript). You can not only change existing elements, but also create new ones and replace or remove old ones as well. These methods are as follows:
• document.createElement('element'): Creates a new element node with the tag name element.
• document.createTextNode('string'): Creates a new text node with the node value of string.
• node.appendChild(newNode): Adds newNode as a new child node to node, following any existing children of node.
• newNode=node.cloneNode(bool): Creates newNode as a copy (clone) of node. If bool is true,the clone includes clones of all the child nodes and attributes of the original.
• node.insertBefore(newNode,oldNode): Inserts newNode as a new child node of node before oldNode.
• node.removeChild(oldNode): Removes the child oldNode from node.
• node.replaceChild(newNode, oldNode): Replaces the child node oldNode of node with newNode.
8) DOM Summary: Your Cheat Sheet
That was a lot to take in, and it might be good to have all the DOM features you need in one place to copy and have on hand, so here you go.
Reaching Elements in a Document
a) document.getElementById('id'): Retrieves the element with the given id as an object
b) document.getElementsByTagName('tagname'): Retrieves all elements with the tag name tagname and stores them in an array-like list.
Reading Element Attributes, Node Values, and Other Node Data
a) node.getAttribute('attribute'): Retrieves the value of the attribute with the name attribute
b) node.setAttribute('attribute', 'value'): Sets the value of the attribute with the name attribute to value
c) node.nodeType: Reads the type of the node (1 = element, 3 = text node)
d) node.nodeName: Reads the name of the node (either element name or #textNode)
e) node.nodeValue: Reads or sets the value of the node (the text content in the case of text nodes)
Navigating Between Nodes
a) node.previousSibling: Retrieves the previous sibling node and stores it as an object.
b) node.nextSibling: Retrieves the next sibling node and stores it as an object.
c) node.childNodes: Retrieves all child nodes of the object and stores them in an list.There are shortcuts for the first and last child node, named node.firstChild and node.lastChild.
d) node.parentNode: Retrieves the node containing node.
Creating New Nodes
a) document.createElement(element): Creates a new element node with the name element.You provide the element name as a string.
b) document.createTextNode(string): Creates a new text node with the node value of string.
c) newNode =node.cloneNode(bool): Creates newNode as a copy (clone) of node. If bool is true, the clone includes clones of all the child nodes of the original.
d) node.appendChild(newNode): Adds newNode as a new (last) child node to node.
e) node.insertBefore(newNode,oldNode): Inserts newNode as a new child node of node before oldNode.
f) node.removeChild(oldNode): Removes the child oldNode from node.
g) node.replaceChild(newNode, oldNode): Replaces the child node oldNode of node with newNode.
h) element.innerHTML: Reads or writes the HTML content of the given element as a string—including all child nodes with their attributes and text content.
9) Changing the Presentation Layer via JavaScript
Every element in the HTML document has as one of its properties a style attribute that is a collection of all its visual properties. You can read or write the attribute’s value, and if you write a value into the attribute, you will immediately change the look and feel of the element.
Example:
exampleStyleChange.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example: Accessing the style collection</title>
<style type="text/css">
</style>
<script type="text/javascript" src="DOMhelp.js"></script>
<script type="text/javascript" src="styleChange.js"></script>
</head>
<body>
<h3>Contact Details</h3>
<address>
Awesome Web Production Company<br />
Going Nowhere Lane 0<br />
Catch 22<br />
N4 2XX<br />
England<br />
</address>
</body>
</html>
styleChange.js
sc={
init:function(){
sc.head=document.getElementsByTagName('h3')[0];
if(!sc.head){return;}
sc.ad=DOMhelp.closestSibling(sc.head,1);
sc.ad.style.display='none';
var t=DOMhelp.getText(sc.head);
var collapseLink=DOMhelp.createLink('#',t);
sc.head.replaceChild(collapseLink,sc.head.firstChild);
DOMhelp.addEvent(collapseLink,'click',sc.peekaboo,false)
collapseLink.onclick=function(){return;} // Safari fix
},
peekaboo:function(e){
sc.ad.style.display=sc.ad.style.display=='none'? '':'none';
DOMhelp.cancelClick(e);
}
}
DOMhelp.addEvent(window,'load',sc.init,false);
The script grabs the first H3 element in the document and gets the ADDRESS element via the closestSibling helper method of the DOMhelp library (the method makes sure that it retrieves the next element and not line breaks that are seen as text nodes). It then modifies the display property of its style collection to hide the address. It replaces the text inside the heading with a link pointing to the function peekaboo. The link is necessary to allow keyboard users to expand and collapse the address. While mouse users could easily click the heading, it is not accessible by tabbing through the document. The peekaboo() function reads the display value of the style collection of the address and replaces it with an empty string if display is set to none and with none when the display is set to something other than an empty string.
10) Select Boxes
Select boxes are probably the most complex and most versatile of form elements. Designers love them, as it lets them store a lot of options for the user to choose from in a small screen space (on the other hand, designers also hate them because they cannot style them with CSS properly).
Each select box has a list object called options that has several properties:
• length: The number of all options inside this select box.
• selected: Boolean if the option is selected by the user.
• selectedIndex: The index number of the selected element. If no element was selected,this returns -1 (which actually is a property of the SELECT element but is appropriate to mention here).
• text: The text content of the option.
• value: The value of the option.
Adding, Replacing, and Removing Options
Select boxes are unique as form elements go, insofar as they allow you to add or remove options programmatically. You can add a new option by using the Option constructor and including it in the list of options:
extraOption = new Option(value, text, defaultSelected, selected);
If you want, for example, to add “DOM scripting” as a subject to the list, you can do so like this:
exampleSelectChoice.html
function addOption(fieldName) {
var f = document.forms[0];
var selectBox = f.elements[fieldName];
var extraOption = new Option('DOM scripting', 'domscripting', 0, 0);
selectBox.options[ selectBox.options.length ] = extraOption;
}
You can remove an option by setting it equal to null:
exampleSelectChoice.html
function removeOption(fieldName,i) {
var f = document.forms[0];
var selectBox = f.elements[fieldName];
selectBox.options[i] = null;
}
Replacing options is as easy; simply set the old option to the new one:
exampleSelectChoice.html
function replaceOption( fieldName, i ) {
var f = document.forms[0];
var selectBox = f.elements[fieldName];
var extraOption = new Option( 'DOM scripting', 'domscripting',➥
0 ,0 );
selectBox.options[i] = extraOption;
}
Inserting an option before another option is a bit more problematic, as you need to copy all the options before you rewrite the options collection. The function insertBeforeOption() takes two parameters: the name of the form element and the index of the option you want to insert the new option before. You start by defining two loop counters called i and j and a blank array called opts before finding the select box and creating the new option.
exampleSelectChoice.html
function insertBeforeOption( fieldName, n ) {
var i = 0, j = 0, opts = [],
var f = document.forms[0];
var selectBox = f.elements[fieldName];
var extraOption = new Option('DOM scripting','domscripting', 0,0);
Then store the options of the select box in a variable called old and loop through them,creating a new option for each of them and assigning their properties to the new option.
exampleSelectChoice.html
var old = selectBox.options;
for( i = 0; i < old.length; i++ ) {
opts[i] = new Option(old[i].text, old[i].value,
old[i].defaultSelected, old[i].selected );
}
The new list will be one element longer, which is why you increase the length property before looping through the new list. You test whether the loop counter is the same as the parameter sent to the function and insert the new option if this is the case.
exampleSelectChoice.html
old.length++;
for( i = 0; i < old.length; i++ ) {
if( i == n ) {
old[i] = extraOption;
} else {
old[i] = opts[j];
j++;
}
}
}
Otherwise, you set the option to the old option and increase the j counter variable. Notice you need a second counter here because you cannot change the variable i during the loop. As the new option list will be one item bigger, you need to use j to get the value stored in the opts array.
exampleSelectChoice.html
Depending on the number of options in the select box, this could become a rather slow and demanding script. You can achieve the same effect a lot quicker and with less code by using the DOM:
exampleSelectChoice.html
function insertBeforeOptionDOM( fieldName, i ) {
var selectBox = document.getElementById( fieldName );
if( !selectBox ){ return false; }
var opt = selectBox.getElementsByTagName( 'option' );
var extraOption = document.createElement( 'option' );
extraOption.setAttribute( 'value', 'domscripting' );
extraOption.appendChild( document.createTextNode(
'DOM Scripting' ) );
selectBox.insertBefore( extraOption, selectBox.options[i] );
}
Select boxes are a big part of web application development and have traditionally been the interface for sorting two lists by moving elements back and forth.
Hope you enjoy reading this book.
About The Author
CHRISTIAN HEILMANN grew up in Germany and, after a year working with people with disabilities for the Red Cross, spent a year as a radio producer. From 1997 onwards, he worked for several agencies in Munich as a web developer. In 2000, he moved to the US to work for eToys and, after the dot-com crash, he moved to the UK where he led the web development department at Agilisys. In April 2006,he joined Yahoo! UK as a web developer. He publishes an almost daily blog at http://wait-till-i.com and runs an article repository at http://icant.co.uk. He is a member of the Web Standards Project’s DOM Scripting Task Force.
No comments:
Post a Comment