Its My Space

Cooooooooooool

Archive for the ‘Javascript’ Category

Using Cookies

Posted by Ramkumar on January 30, 2009

Using Cookies with JavaScript
The document.cookie property is a string that contains all the names and values of Navigator cookies. You can use this property to work with cookies in JavaScript. Here are some basic things you can do with cookies:
• Set a cookie value, optionally specifying an expiration date.
• Get a cookie value, given the cookie name.
It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration:
// Sets cookie values. Expiration date is optional
//

function setCookie(name, value, expire) {
document.cookie = name + “=” + escape(value)
+ ((expire == null) ? “” : (“; expires=” + expire.toGMTString()))
}
Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters. The following function returns a cookie value, given the name of the cookie:
function getCookie(Name) {
var search = Name + “=”
if (document.cookie.length > 0) { // if there are any cookies
offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(“;”, offset)
// set index of end of cookie value
if (end == -1)
end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
Notice the use of unescape to decode special characters in the cookie value.

Using Cookies: an Example
Using the cookie functions defined in the previous section, you can create a simple page users can fill in to “register” when they visit your page. If they return to your page within a year, they will see a personal greeting. You need to define one additional function in the HEAD of the document. This function, register, creates a cookie with the name TheCoolJavaScriptPage and the value passed to it as an argument.
function register(name) {
var today = new Date()
var expires = new Date()
expires.setTime(today.getTime() + 1000*60*60*24*365)
setCookie(“TheCoolJavaScriptPage”, name, expires)
}
The BODY of the document uses getCookie (defined in the previous section) to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page.
<BODY>
<H1>Register Your Name with the Cookie-Meister</H1>
<P>
<SCRIPT>
var yourname = getCookie(“TheCoolJavaScriptPage”)
if (yourname != null)
document.write(“<P>Welcome Back, “, yourname)
else
document.write(“<P>You haven’t been here in the last year…”)
</SCRIPT>
<P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.
<BR>
<FORM onSubmit=”return false”>
Enter your name: <INPUT TYPE=”text” NAME=”username” SIZE= 10><BR>
<INPUT TYPE=”button” value=”Register”
onClick=”register(this.form.username.value); history.go(0)”>
</FORM>

Posted in Javascript | Tagged: | Leave a Comment »

Using the Status Bar

Posted by Ramkumar on January 30, 2009

You can use two window properties, status and defaultStatus, to display messages in the Navigator status bar at the bottom of the window. Navigator normally uses the status bar to display such messages as “Contacting Host…” and “Document: Done.” The defaultStatus message appears when nothing else is in the status bar. The status property displays a transient message in the status bar, such as when the user moves the mouse pointer over a link. You can set these properties to display custom messages. For example, to display a custom message after the document has finished loading, simply set defaultStatus. For example,
defaultStatus = “Some rise, some fall, some climb…to get to Terrapin”
Creating Hints with onMouseOver and onMouseOut
By default, when you move the mouse pointer over a hyperlink, the status bar displays the destination URL of the link. You can set status in the onMouseOut and onMouseOver event handlers of a hyperlink or image area to display hints in the status bar instead. The event handler must return true to set status. For example,
<A HREF=”contents.html”
onMouseOver=”window.status=’Click to display contents’;return true”>
Contents
</A>

Posted in Javascript | Tagged: | Leave a Comment »

Embedding JavaScript in HTML

Posted by Ramkumar on January 30, 2009

You can embed JavaScript in an HTML document as statements and functions within a <SCRIPT> tag, by specifying a file as the JavaScript source, by specifying a JavaScript expression as the value of an HTML attribute, or as event handlers within certain other HTML tags (primarily form elements). This chapter contains the following sections:
• Using the SCRIPT Tag
• Specifying a File of JavaScript Code
• Using JavaScript Expressions as HTML Attribute Values
• Using Quotation Marks
• Specifying Alternate Content with the NOSCRIPT Tag

Using the SCRIPT Tag
The <SCRIPT> tag is an extension to HTML that can enclose any number of JavaScript statements as shown here:
<SCRIPT>
JavaScript statements…
</SCRIPT>
A document can have multiple <SCRIPT> tags, and each can enclose any number of JavaScript statements.
Specifying the JavaScript Version
Each version of Navigator supports a different version of JavaScript. To ensure that users of various versions of Navigator avoid problems when viewing pages that use JavaScript, use the LANGUAGE attribute of the <SCRIPT> tag to specify the version of JavaScript with which a script complies. For example, to use JavaScript 1.2 syntax, you specify the following:
<SCRIPT LANGUAGE=”JavaScript1.2″>
Using the LANGUAGE tag attribute, you can write scripts compliant with earlier versions of Navigator. You can write different scripts for the different versions of the browser. If the specific browser does not support the specified JavaScript version, the code is ignored. If you do not specify a LANGUAGE attribute, the default behavior depends on the Navigator version. The following table lists the <SCRIPT> tags supported by different Netscape versions.

Navigator ignores code within <SCRIPT> tags that specify an unsupported version. For example, Navigator 3.0 does not support JavaScript 1.2, so if a user runs a JavaScript 1.2 script in Navigator 3.0, the script is ignored.
Example 1. This example shows how to define functions three times, once for JavaScript 1.0, once using JavaScript 1.1 features, and a third time using JavaScript 1.2 features.
<SCRIPT LANGUAGE=”JavaScript”>
// Define 1.0-compatible functions such as doClick() here
</SCRIPT>
<SCRIPT LANGUAGE=”JavaScript1.1″>
// Redefine those functions using 1.1 features
// Also define 1.1-only functions
</SCRIPT>
<SCRIPT LANGUAGE=”JavaScript1.2″>
// Redefine those functions using 1.2 features
// Also define 1.2-only functions
</SCRIPT>
<FORM …>
<INPUT TYPE=”button” onClick=”doClick(this)” …>

</FORM>
Example 2. This example shows how to use two separate versions of a JavaScript document, one for JavaScript 1.1 and one for JavaScript 1.2. The default document that loads is for JavaScript 1.1. If the user is running Navigator 4.0, the replace method replaces the page.
<SCRIPT LANGUAGE=”JavaScript1.2″>
// Replace this page in session history with the 1.2 version
location.replace(“js1.2/mypage.html”);
</SCRIPT>
[1.1-compatible page continues here...]
Example 3. This example shows how to test the navigator.userAgent property to determine which version of Navigator 4.0 is running. The code then conditionally executes 1.1 and 1.2 features.
<SCRIPT LANGUAGE=”JavaScript”>
if (navigator.userAgent.indexOf(“4.0″) != -1)
jsVersion = “1.2″;
else if (navigator.userAgent.indexOf(“3.0″) != -1)
jsVersion = “1.1″;
else
jsVersion = “1.0″;
</SCRIPT>
[hereafter, test jsVersion before use of any 1.1 or 1.2 extensions]

Hiding Scripts Within Comment Tags
Only Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment:
<SCRIPT>
<!– Begin to hide script contents from old browsers.
JavaScript statements…
// End the hiding here. –>
</SCRIPT>
Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//). Although you are not required to use this technique, it is considered good etiquette so that your pages do not generate unformatted script statements for those not using Navigator 2.0 or later.
NOTE: For simplicity, some of the examples in this book do not hide scripts.

Example: a First Script
Hello, net!
That’s all, folks.
Notice that there is no difference in appearance between the first line, generated with JavaScript, and the second line, generated with plain HTML.

Specifying a File of JavaScript Code

The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript source (rather than embedding the JavaScript in the HTML). For example:
<SCRIPT SRC=”common.js”>
</SCRIPT>
This attribute is especially useful for sharing functions among many different pages. The closing </SCRIPT> tag is required. JavaScript statements within a <SCRIPT> tag with a SRC attribute are ignored except by browsers that do not support the SRC attribute, such as Navigator 2.

URLs the SRC Attribute Can Specify
The SRC attribute can specify any URL, relative or absolute. For example:
<SCRIPT SRC=”http://home.netscape.com/functions/jsfuncs.js”>
If you load a document with any URL other than a file: URL, and that document itself contains a <SCRIPT SRC=”…”> tag, the internal SRC attribute cannot refer to another file: URL.

Requirements for Files Specified by the SRC Attribute

External JavaScript files cannot contain any HTML tags: they must contain only JavaScript statements and function definitions. External JavaScript files should have the file name suffix .js, and the server must map the .js suffix to the MIME type application/x-javascript, which the server sends back in the HTTP header. To map the suffix to the MIME type, add the following line to the mime.types file in the server’s config directory, and then restart the server.
type=application/x-javascript exts=js
If the server does not map the .js suffix to the application/x-javascript MIME type, Navigator improperly loads the JavaScript file specified by the SRC attribute.

Using JavaScript Expressions as HTML Attribute Values
Using JavaScript entities, you can specify a JavaScript expression as the value of an HTML attribute. Entity values are evaluated dynamically. This allows you to create more flexible HTML constructs, because the attributes of one HTML element can depend on information about elements placed previously on the page. You may already be familiar with HTML character entities by which you can define characters with special numerical codes or names by preceding the name with an ampersand (&) and terminating it with a semicolon (;). For example, you can include a greater-than symbol (>) with the character entity &GT; and a less-than symbol (<) with &LT;. JavaScript entities also start with an ampersand (&) and end with a semicolon (;). Instead of a name or number, you use a JavaScript expression enclosed in curly braces {}. You can use JavaScript entities only where an HTML attribute value would normally go. For example, suppose you define a variable barWidth. You could create a horizontal rule with the specified percentage width as follows:
<HR WIDTH=”&{barWidth};%” ALIGN=”LEFT”>
So, for example, if barWidth were 50, this statement would create the display shown in the following figure.

As with other HTML, after layout has occurred, the display of a page can change only if you reload the page. Unlike regular entities which can appear anywhere in the HTML text flow, JavaScript entities are interpreted only on the right-hand side of HTML attribute name/value pairs. For example, if you have this statement:
<H4>&{myTitle};</H4>
It displays the string myTitle rather than the value of the variable myTitle

Using Quotation Marks
Whenever you want to indicate a quoted string inside a string literal, use single quotation marks (‘) to delimit the string literal. This allows the script to distinguish the literal inside the string. In the following example, the function bar contains the literal “left” within a double-quoted attribute value:
function bar(widthPct) {
document.write(“<HR ALIGN=’left’ WIDTH=” + widthPct + “%>”)
}
Here’s another example:
<INPUT TYPE=”button” VALUE=”Press Me” onClick=”myfunc(‘astring’)”>

Specifying Alternate Content with the NOSCRIPT Tag
Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript. HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support JavaScript; code within the tag is ignored by Navigator. Note however, that if the user has disabled JavaScript from the Advanced tab of the Preferences dialog, Navigator displays the code within the <NOSCRIPT> tag. The following example shows a <NOSCRIPT> tag.
<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape Navigator 2.0
or later!
<BR>
<A HREF=”http://home.netscape.com/comprod/mirror/index.html”>
<IMG SRC=”NSNow.gif”></A>
If you are using Navigator 2.0 or later, and you see this message,
you should enable JavaScript by on the Advanced page of the
Preferences dialog box.
</NOSCRIPT>

Posted in Javascript | Tagged: | Leave a Comment »

Working With Objects

Posted by Ramkumar on January 30, 2009

JavaScript is designed on a simple object-based paradigm. An object is a construct with properties that are JavaScript variables or other objects. An object also has functions associated with it that are known as the object’s methods. In addition to objects that are predefined in the Navigator client and the server, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects. This chapter contains the following sections:
• Objects and Properties
• Creating New Objects
• Predefined Core Objects

Objects and Properties
A JavaScript object has properties associated with it. You access the properties of an object with a simple notation:
objectName.propertyName
Both the object name and property name are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named myCar (for now, just assume the object already exists). You can give it properties named make, model, and year as follows:
myCar.make = “Ford”
myCar.model = “Mustang”
myCar.year = 1969;

An array is an ordered set of values associated with a single variable name. Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure. So, for example, you could access the properties of the myCar object as follows:
myCar["make"] = “Ford”
myCar["model"] = “Mustang”
myCar["year"] = 1967

This type of array is known as an associative array, because each index element is also associated with a string value. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object’s name as arguments to the function:
function show_props(obj, obj_name) {
var result = “”
for (var i in obj)
result += obj_name + “.” + i + ” = ” + obj[i] + “\n”
return result
}
So, the function call show_props(myCar, “myCar”) would return the following:
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1967

Creating New Objects
JavaScript has a number of predefined objects. In addition, you can create your own objects. In JavaScript 1.2, you can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object using that function and the new operator.
Using Object Initializers
In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. “Object initializer” is consistent with the terminology used by C++. The syntax for an object using an object initializer is:
objectName = {property1:value1, property2:value2,…, propertyN:valueN}
where objectName is the name of the new object, each propertyI is an identifier (either a name, a number, or a string literal), and each valueI is an expression whose value is assigned to the propertyI. The objectName and assignment is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the object literal. In addition, an initializer used in a function is created each time the function is called. The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.
if (cond) x = {hi:”there”}
The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.
myHonda = {color:”red”,wheels:4,engine:{cylinders:4,size:2.2}}
You can also use object initializers to create arrays. See “Array Literals” on page 37. JavaScript 1.1 and earlier versions. You cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose.

Using a Constructor Function
Alternatively, you can create an object with these two steps:
1. Define the object type by writing a constructor function.
2. Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, year, and color. To do this, you would write the following function:
function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
Notice the use of this to assign values to the object’s properties based on the values passed to the function. Now you can create an object called mycar as follows:
mycar = new car(“Eagle”, “Talon TSi”, 1993)
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string “Eagle”, mycar.year is the integer 1993, and so on. You can create any number of car objects by calls to new. For example,
kenscar = new car(“Nissan”, “300ZX”, 1992)
vpgscar = new car(“Mazda”, “Miata”, 1990)
An object can have a property that is itself another object. For example, suppose you define an object called person as follows:
function person(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
and then instantiate two new person objects as follows:
rand = new person(“Rand McKinnon”, 33, “M”)
ken = new person(“Ken Jones”, 39, “M”)
Then you can rewrite the definition of car to include an owner property that takes a person object, as follows:
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
}
To instantiate the new objects, you then use the following:
car1 = new car(“Eagle”, “Talon TSi”, 1993, rand)
car2 = new car(“Nissan”, “300ZX”, 1992, ken)
Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:
car2.owner.name
Note that you can always add a property to a previously defined object. For example, the statement
car1.color = “black”
adds a property color to car1, and assigns it a value of “black.” However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

Indexing Object Properties
In JavaScript 1.0, you can refer to an object’s properties by their property name or by their ordinal index. In JavaScript 1.1 or later, however, if you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index. This applies when you create an object and its properties with a constructor function, as in the above example of the Car object type, and when you define individual properties explicitly (for example, myCar.color = “red”). So if you define object properties initially with an index, such as myCar[5] = “25 mpg”, you can subsequently refer to the property as myCar[5]. The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of “myForm”, you can refer to the form as document.forms[1] or document.forms["myForm"] or document.myForm.

Defining Properties for an Object Type
You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1.
Car.prototype.color=null
car1.color=”black”

Defining Methods
A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:
object.methodname = function_name
where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function. You can then call the method in the context of the object as follows:
object.methodname(params);
You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,
function displayCar() {
var result = “A Beautiful ” + this.year + ” ” + this.make
+ ” ” + this.model
pretty_print(result)
}
where pretty_print is function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs. You can make this function a method of car by adding the statement
this.displayCar = displayCar;
to the object definition. So, the full definition of car would now look like
function car(make, model, year, owner) {
this.make = make
this.model = model
this.year = year
this.owner = owner
this.displayCar = displayCar
}
Then you can call the displayCar method for each of the objects as follows:
car1.displayCar()
car2.displayCar()

Using this for Object References
JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have a function called validate that validates an object’s value property, given the object and the high and low values:
function validate(obj, lowval, hival) {
if ((obj.value < lowval) || (obj.value > hival))
alert(“Invalid Value!”)
}
Then, you could call validate in each form element’s onChange event handler, using this to pass it the form element, as in the following example:
<INPUT TYPE=”text” NAME=”age” SIZE=3
onChange=”validate(this, 18, 99)”>
In general, this refers to the calling object in a method. When combined with the form property, this can refer to the current object’s parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form’s name. The button’s onClick event handler uses this.form to refer to the parent form, myForm.
<FORM NAME=”myForm”>
Form name:<INPUT TYPE=”text” NAME=”text1″ VALUE=”Beluga”>
<P>
<INPUT NAME=”button1″ TYPE=”button” VALUE=”Show Form Name”
onClick=”this.form.text1.value=this.form.name”>
</FORM>

Deleting Objects
You can remove an object by using the delete operator. The following code shows how to remove an object.
myobj=new Number()
delete myobj // removes the object and returns true

Predefined Core Objects
This section describes the predefined objects in core JavaScript: Array, Boolean, Date, Function, Math, Number, RegExp, and String.

Array Object
JavaScript does not have an explicit array data type. However, you can use the predefined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions. An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp that contains employees’ names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

Creating an Array
To create an Array object:
1. arrayObjectName = new Array(element0, element1, …, elementN)
2. arrayObjectName = new Array(arrayLength)
arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a property of an existing object. element0, element1, …, elementN is a list of values for the array’s elements. When this form is specified, the array is initialized with the specified values as its elements, and the array’s length property is set to the number of arguments. arrayLength is the initial length of the array. The following code creates an array of five elements:
billingMethod = new Array(5)
Array literals are also Array objects; for example, the following literal is an Array object. See “Array Literals” on page 37 for details on array literals.
coffees = ["French Roast", "Columbian", "Kona"]

Populating an Array
You can populate an array by assigning values to its elements. For example,
emp[1] = “Casey Jones”
emp[2] = “Phil Lesh”
emp[3] = “August West”
You can also populate an array when you create it:
myArray = new Array(“Hello”, myVar, 3.14159)

Referring to Array Elements
You refer to an array’s elements by using the element’s ordinal number. For example, suppose you define the following array:
myArray = new Array(“Wind”,”Rain”,”Fire”)
You then refer to the first element of the array as myArray[0] and the second element of the array as myArray[1]. The index of the elements begins with zero (0), but the length of array (for example, myArray.length) reflects the number of elements in the array.

Array Methods
The Array object has the following methods:
• concat joins two arrays and returns a new array.
• join joins all elements of an array into a string.
• pop removes the last element from an array and returns that element.
• push adds one or more elements to the end of an array and returns that last element added.
• reverse transposes the elements of an array: the first array element becomes the last and the last becomes the first.
• shift removes the first element from an array and returns that element
• slice extracts a section of an array and returns a new array.
• splice adds and/or removes elements from an array.
• sort sorts the elements of an array.
• unshift adds one or more elements to the front of an array and returns the new length of the array.
For example, suppose you define the following array:
myArray = new Array(“Wind”,”Rain”,”Fire”)
myArray.join() returns “Wind,Rain,Fire”; myArray.reverse transposes the array so that myArray[0] is “Fire”, myArray[1] is “Rain”, and myArray[2] is “Wind”. myArray.sort sorts the array so that myArray[0] is “Fire”, myArray[1] is “Rain”, and myArray[2] is “Wind”.

Two-Dimensional Arrays
The following code creates a two-dimensional array.
a = new Array(4)
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
a[i][j] = “["+i+","+j+"]“
}
}
The following code displays the array:
for (i=0; i < 4; i++) {
str = “Row “+i+”:”
for (j=0; j < 4; j++) {
str += a[i][j]
}
document.write(str,”<p>”)
}
This example displays the following results:
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]

Arrays and Regular Expressions

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace. For information on using arrays with regular expressions,

Boolean Object
The Boolean object is a wrapper around the primitive Boolean data type. Use the following syntax to create a Boolean object:
booleanObjectName = new Boolean(value)
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

Date Object
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00. The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC. To create a Date object:
dateObjectName = new Date([parameters])
where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The parameters in the preceding syntax can be any of the following:
• Nothing: creates today’s date and time. For example, today = new Date().
• A string representing a date in the following form: “Month day, year hours:minutes:seconds.” For example, Xmas95 = new Date(“December 25, 1995 13:30:00″). If you omit hours, minutes, or seconds, the value will be set to zero.
• A set of integer values for year, month, and day. For example, Xmas95 = new Date(1995,11,25). A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(1995,11,25,9,30,0).
JavaScript 1.2 and earlier versions. The Date object behaves as follows:
• Dates prior to 1970 are not allowed.
• JavaScript depends on platform-specific date facilities and behavior; the behavior of the Date object varies from platform to platform.

Methods of the Date Object
The Date object methods for handling dates and times fall into these broad categories:
• “set” methods, for setting date and time values in Date objects.
• “get” methods, for getting date and time values from Date objects.
• “to” methods, for returning string values from Date objects.
• parse and UTC methods, for parsing Date strings.
With the “get” and “set” methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
• Seconds and minutes: 0 to 59
• Hours: 0 to 23
• Day: 0 (Sunday) to 6 (Saturday)
• Date: 1 to 31 (day of the month)
• Months: 0 (January) to 11 (December)
• Year: years since 1900
For example, suppose you define the following date:
Xmas95 = new Date(“December 25, 1995″)
Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95. The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object. For example, the following code displays the number of days left in the current year:
today = new Date()
endYear = new Date(1995,11,31,23,59,59,999) // Set day and month
endYear.setFullYear(today.getFullYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysLeft = (endYear.getTime() – today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft) //returns days left in the year
This example creates a Date object named today that contains today’s date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days. The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:
IPOdate = new Date()
IPOdate.setTime(Date.parse(“Aug 9, 1995″))

Using the Date Object: an Example
In the following example, the function JSClock() returns the time in the format of a digital clock.
function JSClock() {
var time = new Date()
var hour = time.getHours()
var minute = time.getMinutes()
var second = time.getSeconds()
var temp = “” + ((hour > 12) ? hour – 12 : hour)
temp += ((minute < 10) ? “:0″ : “:”) + minute
temp += ((second < 10) ? “:0″ : “:”) + second
temp += (hour >= 12) ? ” P.M.” : ” A.M.”
return temp
}
The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second. The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour – 13), otherwise simply hour. The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way. Finally, a conditional expression appends “PM” to temp if hour is 12 or greater; otherwise, it appends “AM” to temp.

Function Object
The predefined Function object specifies a string of JavaScript code to be compiled as a function. To create a Function object:
functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)
functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror. arg1, arg2, … argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example “x” or “theForm”. functionBody is a string specifying the JavaScript code to be compiled as the function body. Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled. In addition to defining functions as described here, you can also use the function statement.The following code assigns a function to the variable setBGColor. This function sets the current document’s background color.
var setBGColor = new Function(“document.bgColor=’antiquewhite’”)
To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:
var colorChoice=”antiquewhite”
if (colorChoice==”antiquewhite”) {setBGColor()}
You can assign the function to an event handler in either of the following ways:
1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME=”colorButton” TYPE=”button”
VALUE=”Change background color”
onClick=”setBGColor()”>
Creating the variable setBGColor shown above is similar to declaring the following function:
function setBGColor() {
document.bgColor=’antiquewhite’
}
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:
• The inner function can be accessed only from statements in the outer function.
• The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.

Math Object
The predefined Math object has properties and methods for mathematical constants and functions. For example, the Math object’s PI property has the value of pi (3.141…), which you would use in an application as
Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in radians. The following table summarizes the Math object’s methods

Posted in Javascript | Tagged: | Leave a Comment »

Literals in Javascript

Posted by Ramkumar on January 25, 2009

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

• Array Literals
• Boolean Literals
• Floating-Point Literals
• Integers
• Object Literals
• String Literals

Array Literals
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified. The following example creates the coffees array with three elements and a length of three:
coffees = ["French Roast", "Columbian", "Kona"]
If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called. Array literals are also Array objects. See “Array Object” on page 107 for details on Array objects.
Extra Commas in Array Literals
You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with spaces for the unspecified elements. The following example creates the fish array:
fish = ["Lion", , "Angel"]
This array has two elements with values and one empty element (fish[0] is “Lion”, fish[1] is undefined, and fish[2] is “Angel”): If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element.
myList = ['home', , 'school', ];
In the following example, the length of the array is four, and myList[0] is missing.
myList = [ , 'home', , 'school'];
In the following example, the length of the array is four, and myList[3] is missing. Only the last comma is ignored. This trailing comma is optional.
myList = ['home', , 'school', , ];
Boolean Literals
The Boolean type has two literal values: true and false. Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type.


Floating-Point Literals

A floating-point literal can have the following parts:
• A decimal integer
• A decimal point (“.”)
• A fraction (another decimal number)
• An exponent
The exponent part is an “e” or “E” followed by an integer, which can be signed (preceded by “+” or “-”). A floating-point literal must have at least one digit and either a decimal point or “e” (or “E”). Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12
Integers
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literal consists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. Octal integers can include only the digits 0-7. Some examples of integer literals are: 42, 0xFFF, and -345.


Object Literals

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error. The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (Cars(“honda”)); the third element, the special property, uses an existing variable (Sales).
var Sales = “Toyota”;
function CarTypes(name) {
if(name == “Honda”)
return name;
else
return “Sorry, we don’t sell ” + name + “.”;
}
car = {myCar: “Saturn”, getCar: CarTypes(“Honda”), special: Sales}
document.write(car.myCar); // Saturn
document.write(car.getCar); // Honda
document.write(car.special); // Toyota
Additionally, you can use an index for the object, the index property (for example, 7), or nest an object inside another. The following example uses these options. These features, however, may not be supported by other ECMA-compliant browsers.
car = {manyCars: {a: “Saab”, b: “Jeep”}, 7: “Mazda”}
document.write(car.manyCars.b); // Jeep
document.write(car[7]); // Mazda
String Literals
A string literal is zero or more characters enclosed in double (“) or single (‘) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:
• “blah”
• ‘blah’
• “1234″
• “one line \n another line”

Posted in Javascript | 1 Comment »

Variables in Javascript

Posted by Ramkumar on January 25, 2009

You use variables as symbolic names for values in your application. You give variables names by which you refer to them and which must conform to certain rules. A JavaScript identifier, or name, must start with a letter or underscore (“_”); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters “A” through “Z” (uppercase) and the characters “a” through “z” (lowercase). Some examples of legal names are Number_hits, temp99, and _name.

Declaring Variables
You can declare a variable in two ways:
• By simply assigning it a value. For example, x = 42
• With the keyword var. For example, var x = 42

Evaluating Variables
A variable or array element that has not been assigned a value has the value undefined. The result of evaluating an unassigned variable depends on how it was declared:
• If the unassigned variable was declared without var, the evaluation results in a runtime error.
• If the unassigned variable was declared with var, the evaluation results in the undefined value, or NaN in numeric contexts.
The following code demonstrates evaluating unassigned variables.
function f1() {
return y – 2;
}
f1() //Causes runtime error
function f2() {
return var y – 2;
}
f2() //returns NaN
You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.
var input;
if(input === undefined){
doThis();
} else {
doThat();
}
The undefined value behaves as false when used as a Boolean value. For example, the following code executes the function myFunction because the array element is not defined:
myArray=new Array()
if (!myArray[0])
myFunction()
When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in Boolean contexts. For example:
var n = null
n * 32 //returns 0

Variable Scope
When you set a variable identifier by assignment outside of a function, it is called a global variable, because it is available everywhere in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within the function. Using var to declare a global variable is optional. However, you must use var to declare a variable inside a function. You can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a FRAMESET document, you can refer to this variable from a child frame as parent.phoneNumber.

Posted in Javascript | Leave a Comment »

Values in Javascript

Posted by Ramkumar on January 25, 2009

JavaScript recognizes the following types of values:

  • Numbers, such as 42 or 3.14159.
  • Logical (Boolean) values, either true or false.
  • Strings, such as “Howdy!”.
  • null, a special keyword denoting a null value; null is also a primitive value. Because JavaScript is case sensitive, null is not the same as Null, NULL, or any other variant.
  • undefined, a top-level property whose value is undefined; undefined is also a primitive value.

This relatively small set of types of values, or data types, enables you to perform useful functions with your applications. There is no explicit distinction between integer and real-valued numbers. Nor is there an explicit date data type in JavaScript. However, you can use the Date object and its methods to handle dates. Objects and functions are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

Data Type Conversion

JavaScript is a dynamically typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:

var answer = 42

And later, you could assign the same variable a string value, for example,

answer = "Thanks for all the fish..."

Because JavaScript is dynamically typed, this assignment does not cause an error message. In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

x = "The answer is " + 42 // returns "The answer is 42"
y = 42 + " is the answer" // returns "42 is the answer"

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

"37" - 7 // returns 30
"37" + 7 // returns 377

Posted in Javascript | Leave a Comment »

Functions in javascript

Posted by Ramkumar on January 25, 2009

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure–a set of statements that performs a specific task. To use a function, you must first define it; then your script can call it. This chapter contains the following sections:
• Defining Functions
• Calling Functions
• Using the arguments Array
• Predefined Functions

Defining Functions

A function definition consists of the function keyword, followed by
• The name of the function.
• A list of arguments to the function, enclosed in parentheses and separated by commas.
• The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.
Generally, you should define all your functions in the HEAD of a page so that when a user loads the page, the functions are loaded first. Otherwise, the user might perform an action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error. For example, the following code defines a simple function named square:
function square(number) {
return number * number;
}
The function square takes one argument, called number. The function consists of one statement that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function.
return number * number
All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. However, if you pass an object as a parameter to a function and the function changes the object’s properties, that change is visible outside the function, as shown in the following example:
function myFunc(theObject) {
theObject.make=”Toyota”
}

mycar = {make:”Honda”, model:”Accord”, year:1998}
x=mycar.make // returns Honda
myFunc(mycar) // pass object mycar to the function
y=mycar.make // returns Toyota (prop was changed by the function)

Calling Functions

In a Navigator application, you can use (or call) any function defined in the current page. You can also use functions defined by other named windows or frames. Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows.
square(5)
The preceding statement calls the function with an argument of five. The function executes its statements and returns the value twenty-five. The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The show_props function (defined in “Objects and Properties” on page 100) is an example of a function that takes an object as an argument. A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}
You could then compute the factorials of one through five as follows:
a=factorial(1) // returns 1
b=factorial(2) // returns 2
c=factorial(3) // returns 6
d=factorial(4) // returns 24
e=factorial(5) // returns 120

Using the arguments Array

The arguments of a function are maintained in an array. Within a function, you can address the parameters passed to it as follows:
arguments[i]
functionName.arguments[i]
where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length. Using the arguments array, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don’t know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then treat each argument using the arguments array. For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
function myConcat(separator) {
result=”" // initialize list
// iterate through arguments
for (var i=1; i<arguments.length; i++) {
result += arguments[i] + separator
}
return result
}
You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.
// returns “red, orange, blue, “
myConcat(“, “,”red”,”orange”,”blue”)
// returns “elephant; giraffe; lion; cheetah;”
myConcat(“; “,”elephant”,”giraffe”,”lion”, “cheetah”)
// returns “sage. basil. oregano. pepper. parsley. “
myConcat(“. “,”sage”,”basil”,”oregano”, “pepper”, “parsley”)
Predefined Functions

JavaScript has several top-level predefined functions:
• eval
• isFinite
• isNaN
• parseInt and parseFloat
• Number and String
• escape and unescape
The following sections introduce these functions. See the Client-Side JavaScript Reference for detailed information on all of these functions.
eval Function
The eval function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval is:
eval(expr)
where expr is a string to be evaluated. If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
isFinite Function
The isFinite function evaluates an argument to determine whether it is a finite number. The syntax of isFinite is:
isFinite(number)
where number is the number to evaluate. If the argument is NaN, positive infinity or negative infinity, this method returns false, otherwise it returns true. The following code checks client input to determine whether it is a finite number.
if(isFinite(ClientInput) == true)
{
/* take specific steps */
}
isNaN Function
The isNaN function evaluates an argument to determine if it is “NaN” (not a number). The syntax of isNaN is:
isNaN(testValue)
where testValue is the value you want to evaluate. The parseFloat and parseInt functions return “NaN” when they evaluate a value that is not a number. isNaN returns true if passed “NaN,” and false otherwise. The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly:
floatValue=parseFloat(toFloat)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
}
parseInt and parseFloat Functions
The two “parse” functions, parseInt and parseFloat, return a numeric value when given a string as an argument. The syntax of parseFloat is
parseFloat(str)
where parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns “NaN” (not a number). The syntax of parseInt is
parseInt(str [, radix])
parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used. If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns “NaN.” The parseInt function truncates the string to integer values.
Number and String Functions
The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:
Number(objRef)
String(objRef)
where objRef is an object reference. The following example converts the Date object to a readable string.
D = new Date (430054663215)
// The following returns
// “Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983″

x = String(D)
escape and unescape Functions
The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value. The syntax of these functions is:
escape(string)
unescape(string)

Posted in Javascript | Leave a Comment »

Syntax Rules

Posted by Ramkumar on January 25, 2009

  • Statements may contain a semicolon at the end of them as in C, but it is not necessary unless there are multiple statements on one line. Multiple statements on one line must be separated by a semicolon.
  • JavaScript is case sensitive.
  • Quotes may be single quote (‘) or double quote (“). When embedded within each other they must be used consistently as in the following example.

onMouseOver=”window.status=’To Operating Systems Section’ ;return true”

  • Comments are the same as in C++ with the “//” characters for a single line comment, and the “/*” for the beginning of a multiline comment and the “*/” for the end of a multiline comment.
  • Variables must be defined before they are used.

Posted in Javascript | Leave a Comment »

The Key to Understanding JavaScript Quickly

Posted by Ramkumar on January 25, 2009

The key to a quick understanding of JavaScript lies in the structure of its objects. JavaScript is an object oriented language. Beyond that, it has many similarities to the C programming language. Variables are declared before use but they are not explicitly typecast. The variable type is normally determined by its use. The ability to do anything in a programming language requires functions supported by the language. JavaScript contains a few functions that are not part of objects. These functions are generally for variable type conversion to a specific type along with support of some dialog boxes. The rest of the functionality of JavaScript is contained in its objects. The objects contain:

  1. Methods (Functions)
  2. Parameters (Data or Other objects) – Describe characteristics of the object
  3. Events – Events are tied to objects

JavaScript has basically three types of objects which are:

  • Top level objects
  • Objects that are properties of other objects. (What I call sub objects)

Objects that are not properties of other objects (What I call independent objeects)

JavaScript objects do not have the normal class to subclass relationship, but are contained within one another and they do not inherit properties from each other. JavaScript is a tool to allow manipulation of objects that are already created by the computer system such as “navigator” to access browser characteristics.

Posted in Javascript | Leave a Comment »