Tuesday, 5 August 2008

JavaScript Bible, 6th Edition By Danny Goodman, Michael Morrison

Just now i completed reading JavaScript Bible, 6th Edition By Danny Goodman, Michael Morrison

Nice book written by Danny Goodman, Michael Morrison.I enjoyed working as many examples as i can from this book.

Few points i want to share from the book

1) Of helpers and plug-ins

In the early days of the World Wide Web, a browser needed to present only a few kinds of data before a user’s eyes. The power to render text (tagged with HTML) and images (in popular formats such as GIF and JPEG) was built into browsers intended for desktop operating systems. Not wanting to be limited by those data types, developers worked hard to extend browsers so that data in other formats could be rendered on the client computer. It was unlikely, however, that a browser would ever be built that could download and render, say, any of several sound-file formats.

One way to solve the problem was to allow the browser, upon recognizing an incoming file of a particular type, to launch a separate application on the client machine to render the content. As long as this helper application was installed on the client computer (and the association with the helper program was set in the
browser’s preferences), the browser would launch the program and send the incoming file to that program.Thus, you might have one helper application for a MIDI sound file and another for an animation file.Beginning with Netscape Navigator 2 in early 1996, software plug-ins for browsers enabled developers to extend the capabilities of the browser without having to modify the browser. Unlike a helper application, a
plug-in can enable external content to blend into the document seamlessly.

The most common plug-ins are those that facilitate the playback of audio and video from the server. Audio may include music tracks that play in the background while visiting a page or live (streaming) audio, similar to a radio station. Video and animation can operate in a space on the page when played through a plugin
that knows how to process such data.

Today’s browsers tend to ship with plug-ins that decode the most common sound-file types. Developers of plug-ins for Internet Explorer for the Windows operating system commonly implement plug-ins as ActiveX controls—a distinction that is important to the underpinnings of the operating system but not to the user.Plug-ins and helpers are valuable for more than just audio and video playback. A popular helper application is Adobe Acrobat Reader, which displays Acrobat files that are formatted just as though they were being printed. But for interactivity, developers today frequently rely on Macromedia Corporation’s Flash plug-in.Created using the Macromedia Flash authoring environment, a Flash document can have active clickable
areas and draggable elements. Some authors even simulate artistic video games and animated stories in Flash. A browser equipped with the Flash plug-in displays the content in a rectangular area embedded within the browser page.

2) JavaScript cannot surreptitiously perform any of the following actions:

a) Setting or retrieving the browser’s preferences settings, main window appearance features, action buttons, and printing.

b) Launching an application on the client computer.
c) Reading or writing files or directories on the client or server computer.
d) Capturing live data streams from the server for retransmission.
e) Sending secret e-mails from Web site visitors to you.

3) The DOM in a browser window

window object At the very top of the hierarchy is the window. This object represents the content area of the browser window where HTML documents appear. In a multiple-frame environment,each frame is also a window (but don’t concern yourself with this just yet). Because all document action takes place inside the window, the window is the outermost element of the object hierarchy.Its physical borders contain the document.

navigator object. This is the closest your scripts come to accessing the browser program,primarily to read the brand and version of browser that holds the current document. This object is read-only, protecting the browser from inappropriate manipulation by rogue scripts.

screen object. This is another read-only object that lets scripts learn about the physical environment in which the browser is running. For example, this object reveals the number of pixels high and wide available in the monitor.

history object. Although the browser maintains internal details about the browser’s recent history (such as the list available under the Back button), scripts have no access to the details. At most, this object assists a script in simulating a click of the Back or Forward button.

location object. This object is the primary avenue to loading a different page into the current window or frame. URL information about the window is available under very controlled circumstances so that scripts cannot track access to other web sites.

document object. Each HTML document that gets loaded into a window becomes a document object. The document object contains the content that you are likely to script. Except for the html, head, and body element objects that are found in every HTML document, the precise makeup and structure of the element object hierarchy of the document depend on the content you put into the document.

4) One thing i came to know about javascript is we can access variables which are declared in some other scope as well.for example i thought variable i is not accessible outside the for loop but i was wrong.


<html>
<head>
<title>Extracting Highlighted Radio Button</title>
<script type="text/javascript">
function fullName() {
var form = document.forms[0];
for (var i = 0; i < form.stooges.length; i++) {
if (form.stooges[i].checked) {
break;
}
}
alert("You chose " + form.stooges[i].value + ".");
}
</script>
</head>
<body>
<form>
<p>Select your favorite Stooge:
<input type="radio" name="stooges" value="Moe Howard" checked>Moe
<input type="radio" name="stooges" value="Larry Fine">Larry
<input type="radio" name="stooges" value="Curly Howard">Curly<br>
<input type="button" name="Viewer" value="View Full Name..."
onclick="fullName()"></p>
</form>
</body>
</html>


5) Replacing node content
We can perform text changes via the replaceChild() method or by assigning new text to a text node’s nodeValue property.

Example:


<html>
<head>
<script>
function callMe() {
var oldChild = document.getElementById("emphasis1").childNodes[0];
alert(oldChild.nodeValue);
var newText = document.createTextNode("first");
document.getElementById("emphasis1").replaceChild(newText, oldChild);
}
</script>
</head>
<body>
<p id="emphasis1">Text Child</p>
<input type=button value="Click Me" onclick="callMe()">
</body>
</html>


6) Microsoft was the first to implement the innerHTML property of all element objects starting with Internet Explorer 4.

7) canHaveChildren
Useful in some dynamic content situations, the canHaveChildren property reveals whether a particular element is capable of containing a child (nested) element. Most elements that have start and end tags can contain nested elements. A nested element is referred to as a child of its parent container.

Below example how to use the canHaveChildren property to visually identify elements on a page that can have nested elements.


<html>
<head>
<title>canHaveChildren Property</title>
<script type="text/javascript">

function colorAll() {
var elems = document.getElementsByTagName("*");
for (var i = 0; i < elems.length; i++) {
elems[i].style.color
= "red";
}
}
function
colorChildBearing() {
var
elems = document.getElementsByTagName("*");
for
(var i = 0; i < elems.length; i++) {
if
(elems[i].canHaveChildren) {
elems[i].style.color
= "red";
}
}
}

</script
>

</head>
<body>
<h1>canHaveChildren Property Lab</h1>
<hr />
<form name="input">
<input type="button" value="Color All Elements"
onclick=
"colorAll()" />
<br />
<input type="button" value="Reset" onclick="history.go(0)" /><br />
<input type="button"
value=
"Color Only Elements That Can Have Children"
onclick=
"colorChildBearing()" />

</form>
<br />
<hr />
<form name="output">
<input type="checkbox" checked="checked" />Your basic checkbox <input
type=
"text" name="access2" value="Some textbox text." />

</form>
<table id="myTable" cellpadding="10" border="2">
<tr>
<th>Quantity</th>
<th>Description</th>
<th>Price</th>
</tr>
<tbody>
<tr>
<td width="100">4</td>
<td>Primary Widget</td>
<td>$14.96</td>
</tr>
<tr>
<td>10</td>
<td>Secondary Widget</td>
<td>$114.96</td>
</tr>
</tbody>
</table>
</body>
</html>



8) className indentifier
A class name is an identifier that is assigned to the class attribute of an element. To associate a cascading style sheets (CSS) rule with several elements in a document, assign the same identifier to the class attributes of those elements, and use that identifier (preceded by a period) as the CSS rule’s selector. An element’s className property enables the application of different CSS rules to that element under script control.


<html>
<head>
<title>className Property</title>
<style type="text/css">
.special {font-size:16pt; color:red}
</style>
<script type="text/javascript">

function toggleSpecialStyle(elemID) {
var elem = (document.all) ? document.all(elemID) :
document.getElementById(elemID);
if (elem.className == "") {
elem.className = "special";
} else {
elem.className = "";
}
}
</script>
</head>
<body>
<h1>className Property Lab</h1>
<hr />
<form name="input">
<input type="button" value="Toggle Class Name"
onclick=
"toggleSpecialStyle('head1')" />

</form>
<br />
<h1 id="head1">ARTICLE I</h1>
<p>Congress shall make no law respecting an establishment of religion, or
prohibiting the free exercise thereof; or abridging the freedom of
speech, or of the press; or the right of the people peaceably to
assemble, and to petition the government for a redress of
grievances.</p>
<h1>ARTICLE II</h1>
<p>A well regulated militia, being necessary to the security of a free
state, the right of the people to keep and bear arms, shall not be
infringed.</p>
</body>
</html>



9) firstChild and lastChild properties
W3C DOM-based DOMs are built around an architecture known as a node map. Each object defined by HTML is a node in the map. A node has relationships with other nodes in the document—relationships described in family terms of parents, siblings, and children.

A child node is an element that is contained by another element. The container is the parent of such a child.Just as an HTML element can contain any number of child elements, so can a parent object have zero or more children. A list of those children (returned as an array) can be read from an object by way of its
childNodes property:

Though you can use this array (and its length property) to get a reference to the first or last child node, the firstChild and lastChild properties offer shortcuts to those positions. These are helpful when you wish to insert a new child before or after all of the others, and you need a reference point for the IE insertAdjacentElement() method or other method that adds elements to the document’s node list.


<html>
<head>
<title>firstChild and lastChild Properties</title>
<script type="text/javascript">
// helper function for prepend() and append()
function makeNewLI(txt) {
var newItem = document.createElement("li");
newItem.innerHTML = txt;
return newItem;
}
function prepend(form) {
var newItem = makeNewLI(form.input.value);
var firstLI = document.getElementById("myList").firstChild;
document.getElementById("myList").insertBefore(newItem, firstLI);
}
function append(form) {
var newItem = makeNewLI(form.input.value);
var lastLI = document.getElementById("myList").lastChild;
document.getElementById("myList").appendChild(newItem);
}
function replaceFirst(form) {
var newItem = makeNewLI(form.input.value);
var firstLI = document.getElementById("myList").firstChild;
document.getElementById("myList").replaceChild(newItem, firstLI);
}
function replaceLast(form) {
var newItem = makeNewLI(form.input.value);
var lastLI = document.getElementById("myList").lastChild;
document.getElementById("myList").replaceChild(newItem, lastLI);
}
</script>
</head>
<body>
<h1>firstChild and lastChild Property Lab</h1>
<hr />
<form>
<label>Enter some text to add to or replace in the OL
element:</label><br />
<input type="text" name="input" size="50" /><br />
<input type="button" value="Insert at Top"
onclick=
"prepend(this.form)" />
<input type="button"
value=
"Append to Bottom" onclick="append(this.form)" />
<br />
<input type="button" value="Replace First Item"
onclick=
"replaceFirst(this.form)" />
<input type="button"
value=
"Replace Last Item" onclick="replaceLast(this.form)" />

</form>
<ol id="myList">
<li>Initial Item 1</li>
<li>Initial Item 2</li>
<li>Initial Item 3</li>
<li>Initial Item 4</li>
</ol>
</body>
</html>



10) uniqueID
You can let the WinIE5+ browser generate an identifier (id property) for a dynamically generated element on the page with the aid of the uniqueID property. You should use this feature with care, because the ID it generates at any given time may differ from the ID generated the next time the element is created in the page. Therefore, you should use the uniqueID property when your scripts require an unknown element to have an id property, but the algorithms are not expecting any specific identifier.

To guarantee that an element gets only one ID assigned to it while the object exists in memory, assign the value via the uniqueID property of that same object—not some other object. After you retrieve the uniqueID property of an object, the property’s value stays the same no matter how often you access the property again. In general, you assign the value returned by the uniqueID property to the object’s id property for other kinds of processing.


<html>
<head>
<title>Inserting an WinIE5+ Table Row</title>
<script type="text/javascript">
function addRow(item1) {
if (item1) {
// assign long reference to shorter var name
var theTable = document.getElementById("myTable");
// append new row to the end of the table
var newRow = theTable.insertRow(theTable.rows.length);
// give the row its own ID
newRow.id = newRow.uniqueID;
// declare cell variable
var newCell;
// an inserted row has no cells, so insert the cells
newCell = newRow.insertCell(0);
// give this cell its own id
newCell.id = newCell.uniqueID;
// display the row's id as the cell text
newCell.innerText = newRow.id;
newCell.bgColor = "yellow"
// re-use cell var for second cell insertion
newCell = newRow.insertCell(1);
newCell.id = newCell.uniqueID;
newCell.innerText = item1;
}
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<th>Row ID</th>
<th>Data</th>
</tr>
<tr id="firstDataRow">
<td>firstDataRow</td>
<td>Fred</td>
</tr>
<tr id="secondDataRow">
<td>secondDataRow</td>
<td>Jane</td>
</tr>
</table>
<hr />
<form>
Enter text to be added to the table:<br />
<input type="text" name="input" size="25" /><br />
<input type='button' value='Insert Row'
onclick=
'addRow(this.form.input.value)' />

</form>
</body>
</html>



11) appendChild(elementObject)

The appendChild() method inserts an element or text node (defined by other code that comes before it) as the new, last child of the current element. Aside from the more obvious application of adding a new child element to the end of a sequence of child nodes, the appendChild() method is also practical for building element objects and their content before appending, replacing, or inserting the element into an existing
document. The document.createElement() method generates a reference to an element of whatever tag name you assign as that method’s parameter.

The appendChild() method returns a reference to the appended node object. This reference differs from the object that is passed as the method’s parameter because the returned value represents the object as part of the document rather than as a freestanding object in memory.

12) insertBefore(newChildNodeObject, referenceChildNode)

The insertBefore() method is the W3C DOM syntax for inserting a new child node into an existing element. Node references for both parameters must be valid Node objects.

13) mergeAttributes(“sourceObject”)

The mergeAttributes() method is a convenient way to propagate attributes in newly created elements without painstakingly adding attributes one at a time. When you have an object whose attributes can function as a prototype for other elements, those attributes (except for the id attribute) can be applied to a newly created element instantaneously. The default action of this method is not to duplicate the id or name attributes of the element. However, IE5.5+ introduced an extra Boolean parameter, preserveIDs, that enables you to duplicate these two attributes by setting the parameter to false (true is the default).


<html>
<head>
<title>mergeAttributes() Method</title>
<script type="text/javascript">
function doMerge(form) {
var newPElem = document.createElement("p");
var newInputElem = document.createElement("input");
newInputElem.id = newInputElem.uniqueID;
newInputElem.mergeAttributes(form.field1);
newPElem.appendChild(newInputElem);
form.appendChild(newPElem);
newInputElem.value = newInputElem.outerHTML;
}
// called by onChange event handler of fields
function upperMe(field) {
field.value = field.value.toUpperCase();
}
</script>
</head>
<body
onload=
"document.expandable.field1.value =
document.expandable.field1.outerHTML"
>

<h1>mergeAttributes() Method</h1>
<hr />
<form name="expandable" onsubmit="return false">
<p><input type="button" value="Append Field 'Clone'"
onclick=
"doMerge(this.form)" />
</p>
<p><input type="text" name="field1" id="FIELD1" size="120" value=""
style=
"font-size:9pt" onchange="upperMe(this)" />
</p>
</form>
</body>
</html>



14) onpropertychange

The onpropertychange event fires in WinIE5+ whenever a script modifies an object’s property. This includes changes to the properties of an object’s style. Changing properties by way of the setAttribute() method also triggers this event.

A script can inspect the nature of the property change because the event.propertyName property contains the name (as a string) of the property that was just changed. In the case of a change to an object’s style object, the event.propertyName value begins with “style.” as in style.backgroundcolor.

Example:


<html>
<head>
<title>onpropertychange Event Handler</title>
<script type="text/javascript">
function normalText() {
myP.innerText = "This is a sample paragraph.";
}
function shortText() {
myP.innerText = "Short stuff.";
}
function normalColor() {
myP.style.color = "black";
}
function hotColor() {
myP.style.color = "red";
}
function showChange() {
var objID = event.srcElement.id;
var propName = event.propertyName;
var newValue = eval(objID + "." + propName);
status = "The " + propName + " property of the " + objID;
status += " object has changed to \"" + newValue + "\".";
}
</script>
</head>
<body>
<h1>onpropertychange Event Handler</h1>
<hr />
<p id="myP" onpropertychange="showChange()">This is a sample
paragraph.</p>
<form>
Text: <input type="radio" name="btn1" checked="checked"
onclick=
"normalText()" />
Normal <input type="radio" name="btn1"
onclick=
"shortText()" />
Short<br />
Color: <input type="radio" name="btn2" checked="checked"
onclick=
"normalColor()" />
Black <input type="radio" name="btn2"
onclick=
"hotColor()" />
Red
</form>
</body>
</html>


15) onselectstart

The onselectstart event handler fires when a user begins to select content on the page. Selected content can be inline text, images, or text within an editable text box. If the user selects more than one object, the event fires in the first object affected by the selection.

Example


<html>
<head>
<title>onselectstart Event Handler</title>
<style type="text/css">
td {text-align:center}
</style>
<script type="text/javascript">
function showObj() {
var objID = event.srcElement.id;
status = "Selection started with object: " + objID;
}
</script>
</head>
<body id="myBody" onselectstart="showObj()">
<h1 id="myH1">
onselectstart Event Handler
</h1>
<hr id="myHR" />
<p id="myP">This is a sample paragraph.</p>
<table border="1">
<tr id="row1">
<th id="header1">Column A</th>
<th id="header2">Column B</th>
<th id="header3">Column C</th>
</tr>
<tr id="row2">
<td id="cellA2">text</td>
<td id="cellB2">text</td>
<td id="cellC2">text</td>
</tr>
<tr id="row3">
<td id="cellA3">text</td>
<td id="cellB3">text</td>
<td id="cellC3">text</td>
</tr>
</table>
</body>
</html>


16) anchors[]

Anchor objects are points in an HTML document marked with
tags. Anchor objects are referenced in URLs by a hash value between the page URL and anchor name. Like other object properties that contain a list of nested objects, the document.anchors property delivers an indexed array of anchors in a document. Use the array references to pinpoint a specific anchor for retrieving any anchor property.

Example:


<html>
<head>
<title>document.anchors Property</title>
<script type="text/javascript">
function goNextAnchor(where) {
window.location.hash = where;
}
// bind the event handlers
function addEvent(elem, evtType, func) {
if (elem.addEventListener) {
elem.addEventListener(evtType, func, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + evtType, func);
} else {
elem["on" + evtType] = func;
}
}
addEvent(window, "load", function() {
addEvent(document.getElementById("next1"), "click",
function(evt) {goNextAnchor("sec1")});
addEvent(document.getElementById("next2"), "click",
function(evt) {goNextAnchor("sec2")});
addEvent(document.getElementById("next3"), "click",
function(evt) {goNextAnchor("sec3")});
addEvent(document.getElementById("next4"), "click",
function(evt) {goNextAnchor("start")});
});
</script>
</head>
<body>
<h1><a id="start" name="start">Top</a></h1>
<form>
<input type="button" id="next1" name="next" value="NEXT" />
</form>
<hr />
<h1><a id="sec1" name="sec1">Section 1</a></h1>
<form>
<input type="button" id="next2" name="next" value="NEXT" />
</form>
<hr />
<h1><a id="sec2" name="sec2">Section 2</a></h1>
<form>
<input type="button" id="next3" name="next" value="NEXT" />
</form>
<hr />
<h1><a id="sec3" name="sec3">Section 3</a></h1>
<form>
<input type="button" id="next4" name="next" value="BACK TO TOP" />
</form>
<hr />
<p>
<script type="text/javascript">
document.write("<i>There are " + document.anchors.length + " anchors defined for this document<\/i>");
</script>
</p>
</body>
</html>



17) elementFromPoint(x, y)

The IE-specific elementFromPoint() method returns a reference to whatever element object occupies the point whose integer coordinates are supplied as parameters to the method. The coordinate plane is that of the document, whose top-left corner is at point 0,0. This coordinate plane can be very helpful in interactive designs that need to calculate collision detection between positioned objects or mouse events.

18) document.write()

If you are writing to a different frame or window, you are free to use multiple document.write() statements if you like. Whether your script sends lots of small strings via multiple document.write() methods or assembles a larger string to be sent through one document.write() method depends partly on the situation
and partly on your own scripting style.

Example

script37.html


<html>
<head>
<title>Writin' to the doc</title>
</head>
<frameset rows="50%,50%">
<frame name="Frame1" src="script38.html" />
<frame name="Frame2" src="script39.html" />
</frameset>
</html>


script38.html


<html>
<head>
<title>Document Write Controller</title>
<script type="text/javascript">
function takePulse(form) {
var msg = "<html><head><title>On The Fly with " +
form.yourName.value + "<\/title><\/head>";
msg += "<body bgcolor='salmon'><h1>Good Day " + form.yourName.value +
"!<\/h1><hr />";
for (var i = 0; i < form.how.length; i++) {
if
(form.how[i].checked) {
msg
+= form.how[i].value;
break;
}
}
msg
+= "<br />
Make it a great day!<\/body><\/html>";
parent.Frame2.document.write(msg);
parent.Frame2.document.close();
}
function getTitle() {
alert("Lower frame document.title is now:" + parent.Frame2.document.title);
}
// bind the event handlers
function addEvent(elem, evtType, func) {
if (elem.addEventListener) {
elem.addEventListener(evtType, func, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + evtType, func);
} else {
elem["on" + evtType] = func;
}
}
addEvent(window, "load", function() {
addEvent(document.getElementById("enter"), "click",
function(evt) {takePulse(document.getElementById("enter").form)});
addEvent(document.getElementById("peek"), "click", getTitle);
});
</script>
</head>
<body>
Fill in a name, and select how that person feels today. Then click "Write
To Below" to see the results in the bottom frame.
<form>
Enter your first name:<input type="text" name="yourName"
value=
"Dave" />

<p>How are you today? <input type="radio" name="how"
value=
"I hope that feeling continues forever."
checked=
"checked" />
Swell <input type="radio" name="how"
value=
"You may be on your way to feeling Swell" />
Pretty Good
<input type="radio" name="how"
value=
"Things can only get better from here." />
So-So</p>
<p><input type="button" id="enter" name="enter"
value=
"Write To Below" />
</p>
<hr />
<input type="button" id="peek" name="peek"
value=
"Check Lower Frame Title" />

</form>
</body>
</html>


script39.html


<html>
<head>
<title>Placeholder</title>
</head>
<body>
</body>
</html>


19) optgroup Element Object

An optgroup element in the HTML 4.01 specification enables authors to group options into subgroups within a select list. The label assigned to the optgroup element is rendered in the list as a non-selectable item, usually differentiated from the selectable items by some alternate display. In W3C browsers,optgroup items by default are shown in bold italic, whereas all option elements nested within an
optgroup are indented but with normal font characteristics.Browsers not recognizing this element ignore it. All options are presented as if the optgroup elements are not there.

Example:


<html>
<head>
<title>Color Changer 3</title>
<script type="text/javascript">
var regularLabels = ["Reds","Greens","Blues"];
var naturalLabels = ["Apples","Leaves","Sea"];
function setRegularLabels(list) {
var optGrps = list.getElementsByTagName("optgroup");
for (var i = 0; i < optGrps.length; i++) {
optGrps[i].label
= regularLabels[i];
}
}
function
setNaturalLabels(list) {
var
optGrps = list.getElementsByTagName("optgroup");
for
(var i = 0; i < optGrps.length; i++) {
optGrps[i].label
= naturalLabels[i];
}
}
function
seeColor(list) {
var
newColor = (list.options[list.selectedIndex].value);
if
(newColor) {
document.bgColor
= newColor;
}
}
</script
>

</head>
<body onload="seeColor(document.getElementById('colorsList'))">
<form>
<p>Choose a background color: <select name="colorsList"
id=
"colorsList" onchange="seeColor(this)">

<optgroup id="optGrp1" label="Reds">
<option value="#ff9999">Light Red</option>
<option value="#ff3366">Medium Red</option>
<option value="#ff0000">Bright Red</option>
<option value="#660000">Dark Red</option>
</optgroup>
<optgroup id="optGrp2" label="Greens">
<option value="#ccff66">Light Green</option>
<option value="#99ff33">Medium Green</option>
<option value="#00ff00">Bright Green</option>
<option value="#006600">Dark Green</option>
</optgroup>
<optgroup id="optGrp3" label="Blues">
<option value="#ccffff">Light Blue</option>
<option value="#66ccff">Medium Blue</option>
<option value="#0000ff">Bright Blue</option>
<option value="#000066">Dark Blue</option>
</optgroup>
</select></p>
<p><input type="radio" name="labels" checked="checked"
onclick=
"setRegularLabels(this.form.colorsList)" />
Regular Label
Names <input type="radio" name="labels"
onclick=
"setNaturalLabels(this.form.colorsList)" />
Label Names from
Nature</p>
</form>
</body>
</html>


20) String prototype() poroperty:

String objects defined with the new String(“stringValue”) constructor are robust objects compared to run-of-the-mill variables that are assigned string values. You certainly don’t have to create this kind of string object for every string in your scripts, but these objects do come in handy if you find that strings in variables go awry. This happens occasionally while trying to preserve string information as script variables in other frames or windows. By using the string object constructor, you can be relatively assured that the string value will be available in the distant frame when needed.

21) eval(“string”)

Expression evaluation, as you probably are well aware by now, is an important concept to grasp in scripting with JavaScript (and programming in general). An expression evaluates to some value. But occasionally you need to force an additional evaluation on an expression to receive the desired results. The eval() function
acts on a string value to force an evaluation of that string expression. Perhaps the most common application of the eval() function is to convert a string version of an object reference to a genuine object reference.

Example
The eval() function can evaluate any JavaScript statement or expression stored as a string. This includes string equivalents of arithmetic expressions, object value assignments, and object method invocation. I do not recommend that you rely on the eval() function, however, because this function is inherently inefficient
(from the standpoint of performance). Fortunately, you may not need the eval() function to get from a string version of an object’s name to a valid object reference. For example, if your script loops through a series of objects whose names include serial numbers, you can use the object names as array indices rather
than use eval() to assemble the object references. The inefficient way to set the value of a series of fields named data0, data1, and so on, is as follows:


function fillFields() {
var theObj;
for (var i = 0; i < 10; i++) {
theObj = eval(“document.forms[0].data” + i);
theObj.value = i;
}
}
A more efficient way is to perform the concatenation within the index brackets for the object reference:
function fillFields() {
for (var i = 0; i < 10; i++) {
document.forms[0].elements[“data” + i].value = i;
}
}



Hope you enjoy reading this book.

About The Author

Danny Goodman is the author of numerous critically acclaimed and best-selling books, including The Complete HyperCard Handbook, Danny Goodman’s AppleScript Handbook, Dynamic HTML: The Definitive Reference, and JavaScript & DHTML Cookbook. He is a renowned authority and expert teacher of computer scripting languages. His writing style and pedagogy continue to earn praise from readers and teachers around the world. To help keep his finger on the pulse of real-world programming challenges, Goodman frequently lends his touch as consulting programmer and designer to leading-edge World Wide Web and intranet sites from his home base in the San Francisco area.

Michael Morrison is a writer, developer, toy inventor, and author of a variety of books covering topics such as Java, C++, Web scripting, XML, game development, and mobile devices. Some of Michael’s notable writing projects include Faster Smarter HTML and XML, Teach Yourself HTML & CSS in 24 Hours, and Beginning Game Programming. Michael is also the founder of Stalefish Labs (www.stalefishlabs.com), an entertainment company specializing in unusual games, toys, and interactive products

No comments: