You are on page 1of 61

JAVA SCRIPT

HTML is relatively easy to learn, but it is static. It allows the use of links to load new pages, images, sounds, etc., but it provides very little support for any other type of interactivity. To create dynamic material it was necessary to use either:

CGI (Common Gateway Interface) programs Can be used to provide a wide range of interactive features, but... Run on the server, i.e.: A user-action causes a request to be sent over the internet from the client machine to the server.

The server runs a CGI program that generates a new page, based on the information supplied by the client. The new page is sent back to the client machine and is loaded in place of the previous page. Thus every change requires communication back and forth across the internet. Written in languages such as Perl, which are relatively difficult to learn. Java applets Run on the client, so there is no need to send information back and forth over the internet for every change, but... Written in Java, which is relatively difficult to learn.

Netscape Corporation develop a language that: Provides dynamic facilities similar to those available using CGI programs and Java applets. Runs on the Client. Is relatively easy to learn and use.

They came up with JavaScript.

JAVA SCRIPT
Java script is an scripting language and it is an interpreted language whose code can be embedded into an HTML document. .

Java script offers almost all programming facility like built in function to perform math calculation and string manipulation, play sound, open new window etc. Java scrip is case sensitive , particularly in case of identifiers
Java script provides facilities related to document window, frame, form loaded document window and links.

Incorporating JavaScript into HTML


The SCRIPT Tag Every script must be contained inside a SCRIPT container tag. In other words, an opening <SCRIPT> tag starts the script and a closing </SCRIPT> tag ends it: Syntax:<SCRIPT LANGUAGE=JavaScript> > JavaScript program </SCRIPT>

Attributes for the SCRIPT tag.


Attribute Description SRC URL for a file containing the JavaScript source code. The file should have the extension .js.

LANGU AGE

Indicates the language used in the script. In the current version of Navigator this attribute can take only two values: JavaScript and LiveScript. LiveScript is provided for backward compatibility with early scripts developed when the language was called LiveScript. You should use JavaScript in your scripts.

Hiding Scripts from Other Browsers


Browsers that don't support JavaScript will attempt to display or parse the content of the script. In order to avoid this, It recommends the following approach using HTML comments: Syntax:<SCRIPT LANGUAGE="JavaScript"> <!-- HIDE THE SCRIPT FROM OTHER BROWSERS JavaScript program // STOP HIDING FROM OTHER BROWSERS --> </SCRIPT>

Using External Files for JavaScript Programs


To make development and maintenance of HTML files and JavaScript scripts easier, the JavaScript specification includes the option of keeping your JavaScript scripts in separate files and using the SRC attribute of the SCRIPT tag to include the JavaScript program in an HTML file.

Syntax:<SCRIPT LANGUAGE="JavaScript SRC="JavaScript1.js"> </SCRIPT>

The JavaScript Language


JavaScript's data types. Type Example Numbers Any number, such as 17, 21.5, or 54e7 Strings Boolean Null "Greetings!" or 'Fun!' Either true or false A special keyword for exactly that-the null value (that is, nothing)

Declaring Variables You can declare a variable using the var command: var example; It is also possible to assign value to a variable when you declare it: var example = "An Example";

Operators
Arithmetic Operators The standard binary arithmetic operators are : addition (+), subtraction (-), multiplication (*), and division (/). In addition to these basic operators is the modulus (%) operator, calculates the remainder after dividing its operands. Logical Operators Operator Description

&&
|| !

Logical "and"-returns true when both operands are true; otherwise it returns false. Logical "or"-returns true if either operand is true. It only returns false when both operands are false. Logical "not"-returns true if the operand is false and false if the operand is true. This is a unary operator and precedes the operand.

Comparison operators
Operato Description r == != > < >= Returns true if the operands are equal Returns true if the operands are not equal Returns true if the left operand is greater than the right operand Returns true if the left operand is less than the right operand

Returns true if the left operand is greater than or equal to the right operand
Returns true if the left operand is less than or equal to the right operand

<=

Conditional Operators conditional expression can evaluate to one of two different values based on a condition. Syntax:(condition) ? val1 : val2

String Operators Concatenation operator (+) returns the union of two strings. Example:"Welcome to " + "Netscape Navigator evaluates to a single string with the value "Welcome to Netscape Navigator."

Using Functions in Java Script


Functions offer the ability for programmers to group together program code that performs a specific task-or function-into a single unit that can be used repeatedly throughout a program A function is defined as:function function_name(arguments) { command block }

Passing Parameters

Example:In the following function, you can see that printName() accepts one argument called name:

function printName(name) { document.write("<HR>Your Name is <B><I>"); document.write(name); document.write("</B></I><HR>"); }


if you call printName() with the command: printName("Bob"); then, when printName() executes, the value of name is "Bob".

Building Objects in JavaScript


Functions are used to create custom objects. Such functions are called constructor function.

Defining an Object's Properties Before creating a new object, it is necessary to define that object by its properties. This is done by using a function that defines the name and properties of the function.
If you want to create an object type for students,you could create an object named student with properties for name, age, and grade. function student(name,age, grade) { this.name = name; this.age = age; this.grade = grade; }

Using this function, it is now possible to create an object using the new statement: student1 = new student("Bob",10,75); To display he data, following statement can be entered in the script document.write(student1.name); document.write(student1.age); document.write(student1.grade); Objects as Properties of Objects You can also use objects as properties of other objects. For instance, if you were to create an object called grade

function grade (math, english, science) { this.math = math; this.english = english; this.science = science; } you could then create two instances of the grade object for the two students: bobGrade = new grade(75,80,77); janeGrade = new grade(82,88,75); Using these objects, you could then create the student objects like this: student1 = new student("Bob",10,bobGrade); student2 = new student("Jane",9,janeGrade); You could then refer to Bob's math grade as document.write(student1.grade.math);

Adding Methods to Objects We can add a method to an object definition. To create method first we need to create a function that defines the method you want to add to your object definition. For instance, if you want to add a method to the student object to print the student's detail to the document window,we could create a function called displayProfile(): function displayProfile() { document.write("Name: " + this.name + "<BR>"); document.write("Age: " + this.age + "<BR>"); document.write("Math Grade: " + this.grade.math + "<BR>"); document.write("English Grade: " + this.grade.english + "<BR>"); document.write("Science Grade: " + this.grade.science + "<BR>"); }

Having defined the method, we now need to change the object definition to include the method:

function student(name,age, grade) { this.name = name; this.age = age; this.grade = grade; this.displayProfile = displayProfile; }
Then, we could output Bob's student profile by using the command: student1.displayProfile();

Java Script Object Model


An object is a set of variables, functions, etc., that are in some way related. They are grouped together and given a name Objects may have: Properties

A variable (numeric, string or Boolean) associated with an object. Most properties can be changed by the user.
Example: the title of a document Methods Functions associated with an object. Can be called by the user. Example: the alert() method

Events

Notification that a particular event has occurred. Can be used by the programmer to trigger responses.
Example: the onClick() event.

Java script interacts with browsers through browsers object model. It is as follows
WINDOW

HISTORY

DOCUMENT

LOCATION

link

anchor

layer

Form

applet

image

area

The hierarchy includes full reference. E.g. To access the form object the path is window.document.form.

The Window Object Window is the fundamental object in the browser. It represents the browser window in which the document appears Methods:alert(string):-Displays a message in a dialog box with an OK button. confirm() :-Displays a message in a dialog box with OK and Cancel buttons. This returns true when the user clicks on OK, false otherwise. close() :-Closes the current window. eval(string):-Evaluates string and removes the value.

blur():- Removes focus from a window. focus() :-Gives input focus to a window. In most versions of Navigator, this brings the window to the front open(argument) :-Opens a new window with a specified document or opens the document in the specified named window. prompt(string,default ) :-Displays a message in a dialog box along with a text entry field. setTimeout(expression,msec) :-Sets a timer for a specified number of milliseconds and then evaluates an expression when the timer has finished counting.

Events:onLoad():- triggered when document is loaded into a window.

onUnload():- triggered when a document is closed or replaced with another document.


onBlur():- triggered when focus is removed from a window.

onFocus():- triggered when focus is applied on a window.


onError():- triggered when an error occurs.

Properties:defaultStatus:-The default value displayed in the status bar. status :-The value of the text displayed in the window's status bar. This can be used to display status messages to the user. Self:-The current window-use this to distinguish between windows and forms of the same name.

Top:-The top-most parent window.


parent :-The FRAMESET in a FRAMESET-FRAME relationship.

Opener:-Refers to the window containing the document that opened the current document.
Length:-number of frames in the current window.

frames :-Array of objects containing an entry for each child frame in a frameset document.

Opening and Closing Windows By using the open() and close() methods, you have control over what windows are open and which documents they contain. Syntax:window.open("URL", "windowName", "featureList"); Here the feature List is a comma-separated list containing any of the entries Name toolbar location directories status menubar scrollbars resizable Description Creates the standard toolbar Creates the location entry field Creates the standard directory buttons Creates the status bar Creates the menu at the top of the window Creates scroll bars when the document grows beyond the current window Enables resizing of the window by the user

width height

Specifies the window width in pixels Specifies the window height in pixels

Example:window.open("new.html","newWindow","toolbar=yes, location=1,directories=yes,status=yes,menubar=1, scrollbars=yes,resizable=0,copyhistory=1,width=200, height=200");

The close() method is simpler to use: Example:window.close(); simply closes the current window.

The location Object The location object provides several properties and methods for working with the location of the current object. Properties:Name hash Description The anchor name (the text following a # symbol in an HREF attribute) host The hostname and port of the URL hostname The hostname of the URL href The entire URL as a string pathname The file path (the portion of the URL following the third slash) port The port number of the URL (if there is no port number, then the empty string) protocol The protocol part of the URL (such as http:, gopher: or ftp:-including the colon)

search

The form data or query following the question mark (?) in the URL

Methods:reload() Reloads the current URL

replace() Loads the a new URL over the current entry in the history list
Syntax:Window.location.property/method([parameter]) Example:Parent.location:-URL information of parent window

The History Object The history object allows a script to work with the Navigator browser's history list in JavaScript. This object maintains the history list in an array and individual items can be accessed through their indices. Example:-window.history[4] Properties:Next,current and previous:-next,current,and previous list in the list Length:- An integer representing the number of items on the history list

Methods:back():- Goes back to the previous document in the history list. forward():- Goes forward to the next document in the history list. go(location):- Goes to the document in the history list specified by location. location can be a string or integer value. If it is a string, it represents all or part of a URL in the history list. If it is an integer, location represents the relative position of the document on the history list. As an integer, location can be positive or negative.

The Date Object The Date object provides mechanisms for working with dates and times in JavaScript. Instances of the object can be created as Syntax:newObjectName = new Date() Methods:getDate() Returns the day of the month for the current Date object as an integer from 1 to 31. getDay() Returns the day of the week for the current Date object as an integer from 0 to 6 (where 0 is Sunday, 1 is Monday) getHours() Returns the hour from the time in the current Date object as an integer from 0 to 23. getMinutes() Returns the minutes from the time in the current Date object as an integer from 0 to 59. getMonth() Returns the month for the current Date object as an integer from 0 to 11 (where 0 is January, 1 is February, etc.).

getSeconds() Returns the seconds from the time in the current Date object as an integer from 0 to 59. getTime() Returns the time of the current Date object as an integer representing the number of milliseconds since January 1, 1970 at 00:00:00. getYear() Returns the year for the current Date object as a twodigit integer representing the year minus 1900. setDate(dateValue) Sets the day of the month for the current Date object. dateValue is an integer from 1 to 31. setHours(hoursValue) Sets the hours for the time for the current Date object. hoursValue is an integer from 0 to 23.

setMinutes(minutesValue) Sets the minutes for the time for the current Date object. minutesValue is an integer from 0 to 59. setMonth(monthValue) Sets the month for the current Date object. monthValue is an integer from 0 to 11 (where 0 is January, 1 is February, etc.). setSeconds(secondsValue) Sets the seconds for the time for the current Date object. secondsValue is an integer from 0 to 59. setTime(timeValue) Sets the value for the current Date object. timeValue is an integer representing the number of milliseconds since January 1, 1970 at 00:00:00. setYear(yearValue) Sets the year for the current Date object. yearValue is an integer greater than 1900.

The Math Object The Math object provides properties and methods for advanced mathematical calculations. Syntax to access properties & methods:Math.property Math.method(value) Properties and methods of the Math object. Name Description

LN10

The natural logarithm of 10 (roughly 2.302).

LN2
PI

The natural logarithm of 2 (roughly 0.693).


The ratio of the circumference of a circle to the diameter of the same circle (roughly 3.1415).

SQRT1_2 The square root of 1/2 (roughly 0.707).

SQRT2 abs() acos() asin() atan() atan2()

ceil() cos() exp() floor()

The square root of 2 (roughly 1.414). Calculates the absolute value of a number. Calculates the arc cosine of a number-returns result in radians. Calculates the arc sine of a number-returns result in radians. Calculates the arc tangent of a number-returns result in radians. Calculates the angle of a polar coordinate that corresponds to a cartesian (x,y) coordinate passed to the method as arguments. Returns the next integer greater than or equal to a number. Calculates the cosine of a number. Calculates e to the power of a number. Returns the next integer less than or equal to a number

log() max()

Calculates the natural logarithm of a number. Returns the greater of two numbers-takes two arguments. min() Returns the least of two numbers-takes two arguments. pow() Calculates the value of one number to the power of a second number-takes two arguments. random() Returns a random number between zero and one. round() sin() sqrt() tan() Rounds a number to the nearest integer. Calculates the sine of a number. Calculates the square root of a number. Calculates the tangent of a number.

The Document Object The Document object represents the HTML document displayed in a browser window. Properties:-

alinkColor
anchors applets

color of activated links


Array of objects corresponding to each named anchor in a document. Array of objects corresponding to each Java applet included in a document.

bgColor
cookie

the background color as a hexadecimal triplet.


Contains the value of the cookies for the current document.

fgColor

The RGB value of the foreground color as a hexadecimal triplet. forms Array of objects corresponding to each form in a document. images Array of objects corresponding to each inline image included in a document. lastModified A string containing the last date the document was modified. linkColor The RGB value of links as a hexadecimal triplet. links An array of objects corresponding to each link in a document. Links can be hypertext links or clickable areas of an imagemap.

location

referrer title URL VlinkColor

The full URL of the document. This is the same as the URL property. URL should be used instead of location. Contains the URL of the document that called the current document. A string containing the title of the document. The full URL of the document. The RGB value of followed links as a hexadecimal triplet.

Document methods include:

write() :-Allows a string of text to be written to the document.

The Form Object When you create a form in an HTML document, you automatically create a form object with properties, methods and events that relate to the form itself. A separate instance of the form object is created for each form in a document. A form object can be accessed or referred in two ways:1) Using position in the form array Syntax:- document.forms[index] Example:-document.forms[0] 2) Using name of the form Syntax:- document.formname Example:-document.form1

Accessing individual elements and their attributes:All the controls used in a form are referred to as its element e.g: text,checkbox etc. the elements are referred in two ways:By using array:Syntax:- document.form[index].element[index].attribute. Example:- document.form[0].element[0].value.

By using element name:Syntax:- document.formname.elementname.attribute. Example:- document.form1. text1.value.

Properties:Name:-The name of the form, as defined in the HTML <form> tag when the form is created Example:- alert(document.forms[2].name); Method:-The method used to submit the information in the form Example:-alert(document.forms[2].method); Action:-The action to be taken when the form is submitted Example:-alert(document.forms[2].action); Length:-The number of elements (text-boxes, buttons, etc.) in the form. Example:-alert(document.forms[2].length); element:-An array of all the elements in the form Example:alert(document.forms[2].elements[0].name); will display the name of the first element in this form

Methods:Submit():-Submits the form data to the destination specified in the action attribute using the method specified in the method attribute. this method invokes a click on the submit button of a form without invoking the onSubmit event handler. Events:-

onSubmit:-Message sent each time a form is submitted. Can be used to trigger actions (e.g., calling a function). Usually placed within the <form> tags, for example: Example:-<form onSubmit="displayFarewell()">
would cause the function displayFarewell() to execute automatically every time the form is submitted.

Methods of form elements Element Name Method Description Fired when pointer enters the field. Fired when pointer is removed from field Fired when text is selected in the field Fired when values of the field is changed Fired when the element is clicked

Text,password, onFocus() textarea & selection list Text,password, textarea & selection onBlur() list Text,password, onSelect() textarea Text,password, textarea & selection onChange() list Button,Radio,che onClick() ckbox,submit & reset

Working with Form Elements Forms are made up of a variety of elements that enable users to provide information. Buttons, Radio-buttons and Checkboxes properties:Name:-The name of the button, radio-button or checkbox, Value:-The value given to the button when it is created. On standard buttons the value is displayed as a label. On radiobuttons and check-boxes the value is not displayed. Example:-document.forms[2].button1.value = "New value"; Checked:-This property - which is used with radio-buttons and check-boxes but not standard buttons - indicates whether or not the button has been selected by the user. Example:-document.forms[2].checkbox1.checked = true

Length:-Indicates the number of radio buttons in a group Example:- document.forms[index].groupname.length

Methods:Focus():-Give the button focus (i.e., make it the default button that will be activated if the return key is pressed).

Example:-document.forms[2].button2.focus();
Blur():-Removes focus from a button. Example:- document.forms[2].button2.blur();

Click():- Simulates the effect of clicking the button.


Example:-document.forms[2].button2.click();

Events:onClick():-Signal sent when the button is clicked. Can be used to call a function Example:-<input type=button name="button3" value="Click Here" onClick="alert('onClick event received')"> onFocus():-Signal sent when the button receives focus . Example:- <input type=button name="button4" value="Click Here" onFocus="alert('This button is now the default')"> onBlur():- Signal sent when the button loses focus. . Example:-<input type=button name="button5" value="Click Here" onBlur="alert('This button is no longer the default')">

Text-boxes and text-areas properties:Name:-The name of the text-box or text-area as defined in the HTML <input> tag when the form is created

Value:-Whatever is typed-into a text-box by the user. we can obtain any text typed into it using the following line of code:
Example:- alert(document.forms[2].textBox1.value);

Events:onFocus():-Event signal generated when a user clicks in a textbox or text-area. Example:- <input type=text name="textBox2" onFocus="alertOnFocus()"> The function called alertOnFocus() displays an alert box, so clicking in the text-box above should trigger the function and cause the alert to appear. onBlur():- Event signal generated when a user clicks outside a text-box or text-area having previously clicked inside it.

Example<input type=text name="textBox3" onBlur="alertOnBlur()">

The Select Object Selection-boxes behave in a very similar fashion to radiobuttons.They also have a similar set of properties, methods and events. properties:SelectedIndex:-Returns an integer indicating which of a group of options has been selected by the user.

Example:alert(document.forms[2].selectBox1.selectedIndex);
Inside select object 2 properties can be used to access individual options, they are:Example:-Document.forms[0].selectname.options[n]. text Document.forms[0].selectname.options[n].value

Passing form data & element to function


To pass the whole form data to a function as a parameter, this.form is used. Example:- <input type=button name="button3" value="Click Here" onClick=inspect(this.form)> In the above example the current form is passed to the function named inspect To pass individual element to a function only this is used. Example:- <input type=text name=text1" onChange=Upperme(this)> In the above example the current element i.e(textbox) is passed to the function named inspect

The String Object JavaScript includes a String object that allow us to manipulate strings in a variety of ways A String object is created in the following way: Example:- var myString = new String("Hello World"); OR var myString = "Hello World"; Properties:Length:-Returns the length of a string. Example:- var stringLength = document.form1.textBox1.value.length

Methods:charAt():-Returns the character at a specified position in a string. The syntax is: charAt(index) Example:-var thirdCharacter = document.form1.textBox2.value.charAt(2); indexOf():-Searches a string to see if it contains a specified character, and if it does, returns the position of that character. If the specified character occurs more than once in the string, it returns the position of the first occurrence of that character. The syntax is: indexOf(character). Example:-var positionOfC = document.form1.textBox3.value.indexOf("c");

Methods:-

lastIndexOf():-It performs the same function as indexOf(), except that if the specified character occurs more than once in the string, it returns the position of the last occurrence of that character rather than the first.
substring()Returns the portion of a string between two specified positions. The syntax is: substring(start_position, end_position) Example:-var extract = document.form1.textBox4.value.substring(2,5); toLowerCase():-Makes the entire string lowercase. toUpperCase():-Makes the entire string uppercase.

Scripting frames and multiple windows in JavaScript


The object references used with frames and windows are self, frame, top and parent. The browsers window can be spilt into frames and the frames can be further split into sub frames. Each frame created is a separate window object, and all the properties ,methods, and events associated with window object can be applied. The splitting of a window into frames and sub frames is a hierarchy, in which each top level frame is a parent & sublevel frames are the children.

JavaScript provides the frames property of the window object for working with different frames from a script.

The frames property is an array of objects with an entry for each child frame in a parent frameset. The number of frames is provided by the length property. For instance, in a given window or frameset with two frames, you could reference the frames as parent.frames[0] and parent.frames[1]. The index of the last frame could be parent.frames.length.
By using the frames array, you can access the functions and variables in another frame, as well as objects, such as forms and links, contained in another frame. This is useful when building an application that spans multiple frames but that also must be able to communicate between the frames.

Types of reference in Frame hierarchy:-

Parent to child relationship:-To access any of the child frames from the parent document, you could use :Window.frames[n].obj_var_name self.frames[n].obj_var_name OR Window.frame_name.obj_var_name self.frame_name.obj_var_name
Child to Parent relationship:If the immediate one upper level parent frame has to be referenced then Syntax:parent.obj_var_name If the top level parent i.e. browsers window has to be reference then Syntax:top.obj_var_name

Child to child relationship:-A references from a child to its sibling can be done by referring the common parent first and then the sibling Parent .frames[n].obj_var_name OR parent.frame_name.obj_var_name

The area Object The area object reflects an clickable area defined in an imagemap. area objects appear as entries in the links array of the document object. Properties:hash A string value indicating an anchor name from the URL. host A string value reflecting the host and domain name portion of the URL. hostname A string value indicating the host, domain name, and port number from the URL. href A string value reflecting the entire URL. pathname A string value reflecting the path portion of the URL (excluding the host, domain name, port number, and protocol). port A string value indicating the port number from the URL.

search A string value specifying the query portion of the URL (after the question mark). protocol A string value indicating the protocol portion of the URL including the trailing colon. target A string value reflecting the TARGET attribute of the AREA tag.

Event Handlers onMouseOut Specifies JavaScript code to execute when the mouse moves outside the area specified in the AREA tag. onMouseOver Specifies JavaScript code to execute when the mouse enters the area specified in the AREA tag.

You might also like