Vous êtes sur la page 1sur 29

Interface Informatics Pvt.

Ltd ISO 9001: 2008 JavaScript Reference Book


Java Script
Java Script is a powerful programming language for the World Wide Web. It not only enables the development of
truly interactive Web pages, it is also the essential glue that integrates
 Java applets
 ActiveX Controls
 Browser Plug-ins
 Server Scripts and
 Other Web Objects, permitting developers to create distributed applications for use over the Internet and
over corporate intranets as well.
Java Script is supported by Netscape Navigator, Microsoft Internet Explorer, and Opera Software’s Opera
browser. As such, it is an important tool for both current and future Web development.

The Web
 The World Wide Web, or simply the Web for short, is one of the most popular services provided via the
internet.
 The web is the collection of all browsers, servers, files, and browser-accessible services available through
the Internet.
 The most familiar element of the Web is the browser.
 A browser is the user’s window to the web, providing the capability to view Web documents and access Web-
based services and applications.
 The web uses the Internet as its communication medium; it must follow Internet communication protocols.
 A protocol is a set of rules governing the procedures for exchanging information.

HTML
The Hypertext Markup Language, or HTML is, the lingua franca of the Web. It is used to create Web pages and is
similar to the codes used by some word processing programs, notably WordPerfect.
HTML uses ordinary ASCII text files to represent Web pages. The files consist of the text to be displayed and the
tags that specify how the text is to be displayed.

Cascading Style Sheet


Style sheets provide the capability to control the way in which HTML elements are laid out and displayed.

URLSs
 A Uniform Resource Locator, or URL is the notation used to specify the address of the Internet file or service.
 A URL always contains a protocol identifier, such as http, or ftp and a host name, such as
home.hetscape.com

HTTP Protocol
 HTTP is the protocol used for communication between browsers and Web servers.
 HTTP uses a request/response model of communication. A browsers establishes a connection with a server
and sends URL requests to the server.

Several request methods are available. GET, HEAD, and POST are the most commonly used ones.

The GET methods: is used to retrieve the information contained at the specified URL.

The HEAD method: is similar to the GET methods except that when a web server processes a HEAD request it
only returns the HTTP header data and not the information that was the object of the request.

The POST method is used to inform the server that the information appended to the request is to be sent to the
specified URL.

Netscape originally developed a language called Live Script to add a basic scripting capability to both Navigator
and its Web-server
 Java Script supports both Web browser and server scripting.

Secunderabad Railway Station - 7801004784 1/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
 Browser scripts are used to create dynamic Web pages that are more interactive, more responsive, and
more tightly integrated with plug-ins, ActiveX components, and Java applets.
 Java script supports these features by providing special programming capabilities, such as the ability to
dynamically generate HTML and to define custom event-handling functions.
 Java script scripts are included in HTML documents via the HTML<SCRIPT> tag.

Java Script is a script-based programming language that supports the development of both client and server
components of Web-based applications. On the client side, it can be used to write programs that are executed by
a Web browser with in the context of a Web page. On the server side, it can be used to write Web server
programs that can process information submitted by a Web browser and then update the browsers display
accordingly.

Embedding JavaScript is HTML

<script language=‘Javascript’>
Javascript statements
</script>

Example

<html>
<head>
<title>Hello World!</title>
</head>
<body>
<script language=‘Javascript’>
document.write (‘hello World!’);
</script>
</body>
</html>

Exercise:
1. write a JavaScript program to print a greeting message

The Script tag SRC attributes:


<script language=‘Javascript’ src=‘src.js’>
</script>
If the file src.js contains the following code:
<!—begin hiding javascript
document.write (‘This text was generated by code in the src.js file’)
//End hiding Javascript-->

JavaScript Comments:
 The JavaScript language provides comments of its own.
 These comments are used to insert notes and processing descriptions into scripts.
 The Comments are ignored when the statements of a script are parsed by JavaScript enabled browsers.
Single line comments

//This JavaScript comment continues to the end of the line.

/* and */ string are used to identify comments that may span multiple line.

Example:

<html><head><title>Using JavaScript Comments</title></head>


<body>

Secunderabad Railway Station - 7801004784 2/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<script language=‘JavaScript’>
<!—Begin hiding JavaScript’
//document.write(‘hello World!’);
/*document.write(‘hello World!’);
document.write(‘Hello World!’);*/
document.write(‘HELLO WORLD!’);
//End hiding Javascript-->
</script>
</body>
</html>

Output:
HELLO WORLD!

Use of the Document Head

 The head of an HTML document provides a great place to include JavaScript definitions.
 Since the head of a document is processed before its body, placing definitions in the head will cause them to
be defined before they are used.

Example
<html><head><title>Using the HEAD for definition</title>
<script language=‘JavaScript’>
<!—
Greeting=‘hi Web Surfers!’;
//-->
</script>
</head>
<body>
<script language=‘javaScript’>
<!—
Document.write(greeting)
//-->
</script></body></html>
Output
Hi

Generating HTML

By including HTML tags in your JavaScript script, we can also use JavaScript to generate HTML elements that
will be displayed in the current document.

Example
<html><head><title>Using JavaScript to Create HTML tags</title>
<script language=‘JavaScript’>
Greeting=‘<h1>Hi wen surfers!</h1>‘
Welcome=‘<p>Welcome to <cite> Mastering JavaScript and Jscript.</cite></p>
</script>
</head>
<body>
<script language=‘javascript’>
document.write(greeting);
document.write(welcome);
</script>
</body>
</html>
Output

Secunderabad Railway Station - 7801004784 3/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
Hi Web surfers!
Welcome to Mastering JavaScript and Jscript.
Exercise:
1. Write a JavaScript program to design your web site.

Types and Variables


 JavaScript does not require specifying the type of data contained in a variable.
 In fact, the same variable may be used to contain a variety of different values, such as the text string Hello
World!, the integer 13, the floating-point values 3.14 or the logical value true.
 The JavaScript interpreter keeps track of and converts the type of data contained in a variable

Conversion of Logical Values to Numeric Values

JavaScript automatically converts the Boolean values true and false into 1 and 0 when they are used in numerical
expressions.

Example
<html><head><title>Conversion of Logical values to numeric values</title>
</head>
<body>
<script language=‘JavaScript’>
<!—
Document.write(‘true*5+false*7=‘)
Document.write(true*5+false*7)
//-- >
</script>
</body></html>
Output

True*5+false*7=5

String Values:
JavaScript supports for strings of characters
A string is a sequence of zero or more characters that are enclosed by double(‘) or single (‘) quotes
To insert a quote character in a string, we must precede it by the backslash (\) escape character.

Example
<html><head><title>Using Quotes within Strings<\title>
</head>
<body>
<script language=‘javaScript’>
document.write(‘He said,\’that’s mine!)
document.write(‘She said,\’No it\ ‘s not<br>‘
document.write(‘That ‘s all folks’);
</script>
</body>
</html>
Output
He said,?’That’s mine
She said,’no it’s not’
That’s all folks!

Special Formatting Characters:


Character Meaning
\’ single quote
\” double quote

Secunderabad Railway Station - 7801004784 4/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
\\ Backslash
\n new line
\r carriage return
\f form feed
\t horizontal tab
\b backspace
The null value:
The null value is common to all JavaScript types. It is used to set a variable to an initial value that is different from
other valid values

The undefined value


The undefined value indicates that a variable has been created but not assigned a value

Conversion Types:
JavaScript automatically converts values from one type to another when they are used in an expression

 Numeric values are converted to their appropriate string value


 Boolean values are converted to 1 and 0 to support numerical operations
 The null value is converted to ‘null’ for string operations, false for logical operations, and 0 for numerical
operations.

Conversion Functions
Functions are collection of JavaScript code that perform a particular task, and often return a value. A function may
take zero or more parameters.

The eval() function can be used to convert a string expression to a numeric value
Example:
Total=eval(‘432.1*10’)
Output:
4321

The parseInt() function can be used to convert a string expression to an integer.


Unlike eval(), parseInt() returns the first integer contained in the string or 0 if the string does not begin with an
integer.
Example:
parseInt(‘123xyz’)
Output:
123
Example:
parseInt(‘xyz’)
Output:
0

parseFloat() function is similar to the parseInt() function. It returns the fiorst floating-point number constained in a
string or 0 is the string does not begin with a valid floating point number.
Example:
parseFloat(‘2.1e4xyz’)
Output
21000
Example
parseFloat(‘xyz’)
Output:
0
Exercise:
1. Write a JavaScript program to find the sum of two numbers
2. Write a JavaScript program to print your address in a neat format
3. Write a JavaScript program to find the read of circle and rectangle.

Secunderabad Railway Station - 7801004784 5/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book

The Object type and Arrays:


JavaScript supports the Object types. This type referred to as a complex data type because it is built from the
primitive types

Arrays
Arrays are objects that are capable of storing a sequence of values. These values are stored in indexed locations
within the array.

Syntax:
Employee=new Array (5)

In the above variable we can store 5 different names.


Example:
<html><head><title>Using Arrays</title></head>
<body>
<h1 align=‘center’>using Arrays</h1>
<script language=‘JavaScript’>
Employee=new Array(5)
Employee[0]=‘bill’
Employee[1]=‘Bob’
Employee[2]=‘Ted’
Employee[3]=‘Alice’
Employee[4]=‘Sue’
document.write(employee[0]+’<br>‘)
document.write(employee[1]+’<br>‘)
document.write(employee[2]+’<br>‘)
document.write(employee[3]+’<br>‘)
document.write(employee[4])
</script></body></html>

The another way of declaring Array variables


The length of the array is not specified and results in the declaration of an array of length 0. An example of using
this type of array declaration follows:

Syntax:
variabelname=new Array()

This declares an array of length that is used to keep track of customer orders.
Example
Order=new Array()
Initial lingth 0
Order[99]= Widget #457’ The length of the array extended 100
Order[999]= ‘Delux widget set #10’ the array extended to 1000

Constructing Dense Array


A dense array is an array that is initially declared with each element being assigned a specified value. Dense
arrays are used in the same manner as other arrays.

Syntax:

Secunderabad Railway Station - 7801004784 6/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
Arayname=new Array(value0,value1,……………….valuen)
Example:
Day=new Array(‘sun’,’mon’,’tue’,’wed’,’thur’,’fri’,’sat’)

The element of an Array


JavaScript does not place any restrictions on the values of the elements of an array.
These values could be of different types, or could refer to other arrays or objects.

Junk =new Array(“s1”,”s2”,4,3.5,true,false,null.new Array(5,6,7))

This junk array has length 8 and its elements are as follows:
Junk[0]=”s1”
Junk[1]=”s2”
Junk[2]=4
Junk[3]=3.5
Junk[4]=true
Junk[5]=false
Junk[6]=null
Junk[7]=new dense array consisting of the values 5, 6, 7
The three elements of junk[7] can be accessed using a second set of subscripts as follows:
Junk[7][0]=5
Junk[7][1]=6
Junk[7][2]=7

InputBox:
Is used for getting values during runtime
Syntax:
Variablename=prompt(“input message”);
Example:
A=prompt(“Enter your name”)
B=parseInt(prompt(“Enter a numeric value”))

Message Box:
It is used for displaying messages on the window.
Example:
alert(“Good morning”);

Confirmation Box:
It is used for getting confirmation from the user ok, cancel
Example
K=confirm(“Do you want to continue?”)

Exercise:
1. Write a JavaScript program to read 5 students details from that to find the total and result
2. Write a JavaScript program to read a number and find out is it a palindrome or not
3. Write a java script [program to find the employee’s net salary using array.

Operators and Expressions:


An Operator is used to transform one or more values into a single resultant value. The values to which the
operator applies are referred to as operands. The combinations of an operator and its operands is refereed to as
an expression
 Arithmetic (+, -, *, /, %)
 Logical (&&, || !)
 Comparison(<,>,>=.<=.==, !=)
 String
 Bit manipulation(&,|,^)
 Assignment(=)

Secunderabad Railway Station - 7801004784 7/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
 Conditional (?:)
Example
<head>
<title>
Arithmetic OPerators
</title></head>
<body>
<script languge="JavaScript">
a=10;
b=20;
document.write("<font size=5>a+b="+(a+b));
document.write("<br>a-b="+(a-b));
document.write("<br>a*b="+(a*b));
document.write("<br>a/b="+(a/b));
document.write("<br>a%b="+(a%b));
document.write("<br>"+a+"+"+b+"="+(a+b)+"</font>");
</script></body></html>

Example:
<html>
<head><title>Relational Operators</title></head>
<body>
<script languge="JavaScript">
a=10;
b=20;
document.write ("a>b = "+(a>b));
document.write("<br>a &lt b = "+(a<b));
</script></body></html>

Conditional Statements:
The if statement
The if statement provides the capability to alter the course of a program execution based on an
expression that yields a logical value. If the logical value is true, a specified set of statements
is executed. If the logical value is false, a the set of statements is skipped.
If (condition)….else….. If (condition) else if(condition)..else
<html> html>
<head> <head>
<title> <title>If elseif Condition</title>
to Display messages </head>
</title> <body>
</head> <script language="javascript">
<body> var a,b
<script languge="JavaScript"> a=parseInt(prompt("Enter value1"));
a=prompt("Enter ur name"); b=parseInt(prompt("Enter value2"));
b=prompt("enter ur age"); c=parseInt(prompt("Enter value2"));
alert ( "Ur Name is :" + a +" \n Ur age is :" + b); if (a>b && a>c)
if (confirm(" do u want to get another name and age?")) alert (a + " is greater");
{ else if (b>c)
a=prompt("Enter ur name"); alert(b + " is greater");
b=prompt("enter ur age"); else
alert ( "Ur Name is :" + a +" \n Ur age is :" + b); alert(c + " is greater");
} </script>
else </body>
{ </html>
alert ("Thank U");
}
</script>

Secunderabad Railway Station - 7801004784 8/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
</body>
</html>

Looping Statements:
Loop statements are used to repeat the execution of a set of statements while a particular condition is true. Java
script supports three types of loop statement
 while
 do while
 for

Javascript also provides the label, break and continue statements.


Break
Is used to terminate all loop iterations
Continue
Is used to cause a single loop iteration to end immediately and proceed to the next loop iteration
Label
It labels a statement for use with break and continues statements
While do while for
<html> <html> <html>
<head> <head><title> Control <head><title>Control
<title>Control Statements-- to Statements-- to print first 5 even Statements-- to print first 5 even
print first 5 even numbers</title> numbers </title> numbers</title>
</head> </head> </head>
<body> <body> <body>
<script language="javascript"> <script language="javascript"> <script language="javascript">
var i=2; var i=2; var i;
while(i<=10) do for(i=2;i<=10;i=i+2)
{ { {
document.writeln(i + "<br>"); document.writeln( i +"<br>"); document.writeln(i +"<br>");
i=i+2; i=i+2; }
} }while(i<=10); </script>
</script> </script> </body>
</body></html> </body></html> </html>
Output:
2
4
6
8
10

Break continue label


<html> <html> <html>
<head> <head><title> Control <head><title>Control
<title>Control Statements-- to Statements-- to print first 5 even Statements-- to print first 5 even
print first 5 even numbers</title> numbers </title> numbers</title>
</head> </head> </head>
<body> <body> <body>
<script language="javascript"> <script language="javascript"> <script language="javascript">
var i=2; var i=2; var i;
while(i<=10) do for(i=2;i<=10;i=i+2)
{ { {
if (i==6) If(i==6) document.writeln(i +"<br>");
break; Continue; if (i==6);
document.writeln(i + "<br>"); document.writeln(i +"<br>"); goto b;
i=i+2; i=i+2; }
} }while(i<=10); Label b:

Secunderabad Railway Station - 7801004784 9/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
document.writeln(‘The End’); document.writeln(‘The End’); document.writeln(‘The End’);
</script>
</script> </script> </body>
</body> </body> </html>
</html> </html>
Output: Output: Output
2 2 2
4 4 4
The End 8 6
10 The End
The End

Switch:
The switch statement evaluates the expression and determines if any of the values match the expressions value.
if one of them matches, then the statements for that particular case are executed, and statement execution then
continues after the switch statement. If there is no matching value, then the statements for the default case are
executed.
Syntax:
switch(value)
{
case value1:
:::::
break;
case value2:
::::::
break;

case valuen:
::::::
break;
default:
::::::::::::
}
Example:
<html><head><title>Using the Switch Statement</title></head>
<body>
<script language=”JavaScript”>
var a;
a=prompt(“Enter a character”)
switch(a)
{
case ‘a’:
case ‘e’:
case ‘I’:
case ‘o’:
case: ‘u’:
document.writeln(“The given character is a vowel”);
break;
default:
document.writeln(“The given character is not a vowel”);

}
</script>
</body>
</html>

Exercise:

Secunderabad Railway Station - 7801004784 10/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
1. Print your name 10 times in a different heading style.
2. Print the following format
W
We
Wel
Welc
Welco
Welcom
Welcome
3. Write JavaScript program to find the given number is amstrong or not(153)

4. Write a JavaScript program to find the grade of a student from 5 subject marks

5. 1
2 2
3 3 3
4 4 4 4
Etc…..

6. Find First 100 even Numbers

7. Write a program from 1950 to 2015 Count the No of Leap Years and Non Leap Years

8. Factorial of Given Number

9. Sum of N Numbers

10. Print the reverse order of a given number

Functions
Functions are named blocks of statements that are referenced and executed as a unit. data that is required for
the execution of a function may be passed as parameters to the function. Functions may return a value, but are
not required to do so. When a function returns a value the invocation of the function is usually part of an
expression.

Defining a Function:
function functionname(p1,p2….pn)
{
statement;
::::::::::::::::::::::::::::::::::
}
Example:
( Function with no return values)

<html>
<head>
<title>jscript</title>

Secunderabad Railway Station - 7801004784 11/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<script language="javascript">
function sum()
{
sum=0
for(var i=1;i<=5;i++)
sum=sum+i
document.write("<br><br> Function Concept: Sum of 5 Values are= "+sum)
}
</script>
</head>

<body bgcolor="lightblue">
<script language="javascript">
sum()
</script>
</body>
</html>

The return statements:


The return statement is used to return a value as the result of the processing performed by a function.
Syntax:
return expression;
Example:
(Function with return values)

<html>
<head>
<title>jscript</title>
<script language="javascript">
function sum()
{
sum=0
for(i=1;i<=5;i++)
{
sum=sum+i
}
return sum
}
</script>
</head>
<body bgcolor="lightblue">
<script language="javascript">
n=sum();
document.write("<br><br> Function Return Concept Sum of 5 Values are= "+n)
</script>
</body>
</html>

Local variable Declarations:


Variables which are declared inside functions are called as local variables
<html>
<head><title>Global and Local Variables</title>
<script language=”JavaScript”>
function display(y)
{

Secunderabad Railway Station - 7801004784 12/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
var x=y*y
document.write(x+”<br>”);
}
</script></head>
<body>
<script language=”javaScript”>
for(x=0;x<5x++)
{
display(x);
}
</script></body></html>

output:
0
1
4
9
16

The with statement:


The with statement is provided as a convenience to eliminate retyping the name of an object that is to be
referenced in a series of property references and method invocations.
Syntax:
with(variablename)
{
statements;
}

Example:
<html>
<head><title>Global and Local Variables</title>
<script language=”JavaScript”>
with(document)
{
write(“<h1>Welcome</h1>”);
write (“<h2>Welcome</h2>”);
write(“<h3>Welcome</h3>”);
}
</script>
</head>
</html>

The for in statement:

The for in statement is similar to a for statement in that it repeatedly executes a set of statements. However,
instead of iterating the statements based on the loop condition, it executes the statements for all properties that
are defined for an object.
Syntax:
for(variablename in objectname)
{
Statements
}
Example:
for(prop in employee)
{
document.write(prop+”<br>”);
}

Secunderabad Railway Station - 7801004784 13/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
Exercise:
1. Write a program to find the factorial of a given number
2. Write a program to find a given number is Armstrong or not
3. Write a program to do the arithmetic operation based on given operation

The throw, try, and catch statement


An exception is an error that is generated by your script to call attention to a problem that is discovered during the
scripts execution.
The script generated an exception so that the error may be handled and resolved.
In the parlance of exceptions, you generate an exception by throwing it. The code that handles exceptions thrown
by your scripts is referred to as an exception handler.

The throw statement is used to throw an exception.


Its’ syntax follows:
throw expression

The value of expression is used to identify the type of error that occurred. For example, the following statement
throws an exception named BadInputFromUser.

throw “BadInputFromUser”

The try statement and the catch statement work together to support exception handling. Their syntax follows:

try
{
statement(s) where an exception may be thrown
}
catch(errovariable)
{
statement(s) that handle the exception
}

Example:

<html>
<head>
<title>jscript</title>
<script language="javascript">
function prime(n)
{
try
{
if(n<1 || n>15)
throw "It is Out of Range "+n;

for(i=2;i<n;i++)
{
if((n%i)==0)

Secunderabad Railway Station - 7801004784 14/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
{
throw n+" is Divisible by "+ i;
}
document.write("<br>" +n +" is Prime Number ")
}
}
catch(exception)
{
document.write("<br>"+exception)
}
}
</script>
</head>

<body bgcolor="lightblue">
<script language="javascript">
document.write("<br><b> Prime Numbers Testing:</b><br>")
for(n=0;n<=15;n++)
prime(n)
</script></body></html>

Exercise:
1. Write a program to read student 5 subject marks and find the total and result. And also arise an error
whenever the marks will greater than 100
2. Write a program to arise the exception when the day is SUNDAY.

Events:

Events describe actions that occur as the result of user interaction with a Web page or other browser-related
activities.
For example, when a user clicks a hyperlink or a button, or enters data in a form, an event is generated informing
the browser that an action has occurred and that further processing is required. The browser waits for events to
occur, and when they do, it performs whatever processing is assigned to those events. The processing that is
performed in response to the occurrence of an event is known as event handling.
The code that performs this processing is called an event handler.

HTML Element HTML tag Event


All elements Various ****mousemove
Link <a>….. </a> Click, Dblclick, mouseDown, mouseUp, mouseOver
mouseOut, keyDown, keyUp, keyPress
Image <img> Abort, Error, Load, Keydown, Keyup, Keypress
Area <area> Mouseover, Mouseout, Dblclick
Document body <body></body> Click, Dblclick, Keydown, Keyup, Keypress,
Mousedown, Mouseup
Window, frame set, frame <frameset>…</frameset> Error, Focus, Load, Unload, Move, Resize, Dragdrop
<frame>…..</frame>
Form <form>…</form> Submit, Reset
Textfield, password field, <input type=text> Blur, focus, change, select, keydown, keyup, keypress
textarea <input type=”password”>
<textarea></textarea>
Button, <Input type=button> Click, blur, focus, mousedown, mouseup
Submit, reset, radiobutton, <input type=submit> Click, blur, focus
checkbox <input type=reset>
<input type=radio>
<input type=checkbox>

Secunderabad Railway Station - 7801004784 15/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
File upload <input type=file Blur, change, focus
Selection <select>….</select> Blur, change, focus

Example:
OnMouseOver:
The mouse is moved over a link or an area of a client-side image map

<html>
<head>
<title>Events</title>
</head>
<body bgcolor="lightblue">
<a onMouseOver="alert('MouseOver')"><b><u>krishna</b></u></a>
</body>
</html>

OnClick
A link, client-side image map area, or form element is clicked.

<html>
<head>
<title>Events</title>
<script language="javascript">
function fun()
{
alert("Event Occur")
}
</script>
</head>
<body bgcolor="lightblue">
<a href="w:\HELEN\JavaScript\objects\b1.jpg" onclick="fun()">krishna</a>
</body>
</html>
Example:
<html>
<head><title> Button Event</title></head>
<body>
<form><input type="Button" name="Red" value="Red color" ONCLICK='document.bgColor="RED" '></P>
<p>
<input type="Button" name="GREEN" value="GREEN" ONCLICK='document.bgColor="green" '></P>
<p>
<input type="Button" name="BLUE" value="BLUE" ONCLICK='document.bgColor="BLUE" '></P>
</form>
</body>
</html>
OnLoad OnUnload
 An image, document, or frame set is loaded
 The user exits a document or frame set.
Example

<html>
<head><title> Button Event</title></head>
<body>
<form><input type="Button" name="Red" value="Red color" ONCLICK='document.bgColor="RED" '></P>
<p>
<input type="Button" name="GREEN" value="GREEN" ONCLICK='document.bgColor="green" '></P>
<p>

Secunderabad Railway Station - 7801004784 16/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<input type="Button" name="BLUE" value="BLUE" ONCLICK='document.bgColor="BLUE" '></P>
</form>
</body>
</html>
Example:
<html>
<head>
<title>Events</title>
<script language="javascript">
function fun()
{
alert("Event Occur")
}
</script>
</head>
<body bgcolor="lightblue" onLoad="alert('Loading')" onUnload="alert('Unload')" onClick="fun()">
</body>
</html>

OnMouseOut
The mouse is move out of a link or an area of a client-side image map
Example
<html>
<head>
<title>Events</title>
<script language="javascript">
function fun()
{
alert("Event Occured")
}
</script>
</head>
<body bgcolor="lightblue">
<a href="w:\HELEN\JavaScript\objects\b3.jpg" onmouseout="fun()"><b><u>krishna</b></u></a>
</body>
</html>

OnBlur
A document, window, frameset, or form element loses the current input focus.
OnFocus
A document, window, frameset or form element receives the current input focus.

Example
<html>
<head><title>GOT FOCUS</title>
<script language="javascript">
function calculation(form)
{
form.area.value=Math.PI*parseInt(form.radius.value)*parseInt(form.radius.value);
form.circum.value=2*Math.PI*parseInt(form.radius.value);
}
</script>
</head>
<body>
<form>
Enter Radius:<input type="text" name="radius"><br>
Area:<input type="text" name="area" onFocus="calculation(this.form);">

Secunderabad Railway Station - 7801004784 17/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<br>
Circumference:<input type="text" name="circum" >
</form>
</body>
</html>
Handling Image Events
<html>
<head><title>Image Event Handling</title>
<scriopt lanaguage=”JavaScript”>
Function imageLoaded()
{
Document.bgcolor=’#FFFFFF”
Alert(doicument.images[0].src+”has been loaded”)
}
Function imageAborted()
{
Alert(“Hey! You just aborted the loading of the last image!”)
}
Function imageError()
{
Alert(“Error loading image!”)
}
</script>
</head>
<body>
<h1>Image Event Handling</h1>
<p>An Image is loaded after this praragraph</p>
<img src=”image1.gif” onLoad=”imageLoaded()” onAbort=”imageAborted()” onError=”imageError()”>
</body>
</html>

Handling Image Map Events:


Image maps are a popular feature found on many web pages. An image map consists of an image that is divided
into different areas or regions. When the user clicks on a particular location within the image, a connection is
made to the URL associated with that location.

Example:
<html>
<head><title> Image amp Event Handling</title>
<script language=”JavaScript”>
firsttimeonhead=true
function onHead()
{
if(firsttimeonhead)
{
alert(“You’re on myt Head!”)
firsttimeonhead=false
}
}
function myeye()
{
alert(“Be careful or you’ll poke out my eye!”)
}
function mynose()
{
alert(“Asscchhooo!”)
}

Secunderabad Railway Station - 7801004784 18/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
function mymouth()
{
alert(“get out of my mouth!”)
}
</script>
</head>
<body>
<h1>Image Map Event Handling</h1>
<ing src=”blockman.gif” USEMAP=”#blockman”>
<MAP NAME=”blockman”>
<AREA COORDS=”80,88,120,125” HREF=”ch04-10.html” onMouseOver=”myeye()”>
<AREA COORDS=”169,88,120,125” HREF=”ch04-10.html” onMouseOver=”myeye()”>
<AREA COORDS=”124,147,165,181” HREF=”ch04-10.html” onMouseOut=”mynose()”>
<AREA COORDS=”92,210,192,228” HREF=”ch04-10.html” onMouseOut=”mymouth()”>
<AREA COORDS=”6,4,292,266” HREF=”ch04-10.html” onMouseOver=”onHead()”>
</MAP>
</BODY>
</HTML>

Simulating Events
When an event simulation method is invoked, the object to which it refers as if the event is taking place. For
example, button objects hae the click() method that, when invoked, causes the button’s event handler to be
invoked.

<html>
<head><title>Simulating Events</title>
<script>
Function button1clicked()
{
Document.test.button2.click()
}
Function button2clicked()
{
Alert(“Button 2 was clicked”)
}
</script>
</head>
<body>
<form name=”test”>
<iunput type=button name=”button1” value=”Button1” onClick=”button1Clicked()”>
<input type=”Button” name=”button2” value=”Button 2” onClick=”button2clicked()”>
</form>
</body>
</html>

Working with Objects


 JavaScript is an Object Based Language.
 It does not support the basic Object-Oriented Programming capabilities of classification, inheritance,
encapsulation, and information hiding.
 JavaScript is a scripting language, not a full programming language.
 JavaScript is referred to as an object-based language
 JavaScript supports a simple Object model that is supported by a number of predefined objects.

Exercise:

Secunderabad Railway Station - 7801004784 19/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
1. Write a JavaScript program to find the arithmetic operation result based on button click.
2. Write a JavaScript program to design an application format for a particular course and read his/her
qualification and find he/she is eligible for that course or not

What are Objects?


An object consists of two things:
 A collection of properties that contain data
 Methods that enable operations on the data contained in those properties
 Objects are JavaScript data Structures that both contain data and provide functions, referred to as
methods, which are used to perform operations on this data.

The JavaScript Object Model


JavaScript supports a simple object model that is supported by a number of predefined objects. The JavaScript
Object Model centers around the specifications of object types that are used to create specific object instances.
Object types under this model are defined in terms of properties and methods.
 Properties are used to access the data values contained in an object.
 Methods are functions that are used to perform operations on an object.

Using Properties:
Syntax:
Objectname.propertyname
Output
Document.bgcolor=”White”

Using Methods:
Syntax:
Objectname.methodname (parameterlist)
Output
R=Math.random()

Creating Instances of Objects


Syntax:
Variable=new Objectype (parameters)

Output
currentdata=new Date()

Predefined Objects:
Browser
Window
Navigator
Array
Boolean
Date
Function
Math
Number
Object
String

WindowObject
Window object is basic to all browser scripts. Like the navigator object, the window object is top-level object that
is automatically defined by our browser. A separate window object is defined for each window that is opened. The
window object is so important to writing browser scripts that the current window object is assumed by default in
many cases and may be omitted.

Secunderabad Railway Station - 7801004784 20/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
Document.write(“Write this text to the current window”)

Property: Method
Closed Alert
defaultStatus Blur
document clearInterval(interval)
frames clearTimeout(timer)
history close()
Length confirm(text)
location focus()
Name open(url,name,[options])
prompt(text,defaultInput)
offscreen-buffering scroll(x,y)
setInterval(expression,milliseconds)
setTimeout(expression,millisecond)

Working with Timeouts

The setTimeout () and clearTimeout () methods provide a clever way to wait a specified amount of time for a user
to perform a particular action and, if the action does not occur within the specified time perform timeout
processing.

Example:
<html>
<head>
<script>
function startEQ()
{
richter=5
parent.moveBy(0,richter)
parent.moveBy(0,-richter)
parent.moveBy(richter,0)
parent.moveBy(-richter,0)
timer=setTimeout("startEQ()",10)
}
function stopEQ()
{
clearTimeout(timer)
}
</script>
</head>
<body>

<form>
<input type="button" onclick="startEQ()" value="Start an earthquake">
<br />
<br />
<input type="button" onclick="stopEQ()" value="Stop the earthquake">
</form>

</body>
</html>

Working with Intervals

Secunderabad Railway Station - 7801004784 21/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
setInterval() method is similar to setTimeout(). The difference is that setTimeout() executes a function or
expression once, while setInterval() executes it repeatedly.

Example:
<html>
<head>
<title>Using SetInterval()</title>
<script language="JavaScript1.2">
var colorindex=0;
function changecolor()
{
colors=new Array("red","orange","green","blue","brown","purple","gray","white");
document.bgColor=colors[colorindex];
colorindex=(colorindex+1)%8;
}
function startColorChange()
{
setInterval("changecolor()",2000);
}
window.onLoad=startColorChange();
</script>
</head>
<body>
<h1>Changing Background Colors</h1>
<p> <code>The setInterval() </code>method is used to repeatedly change the document background color every
three seconds. </p>
</body>
</html>

The document Object


The document object is a very important JavaScript object. It allows to update a document
that is being loaded and to access the HTML elements contained in a loaded document.
Property: Method
Alink Close
Anchor Open
Applet Write
Area Writeln
Bgcolor
Cookie
Form
Image
Fgcolor
Link
Linkcolor
Title
URL
Vlinkcolor
plugin

Example:
<html>
<head>
<title>Window Object Open/Close Functions</title>
<script language="javascript">
function create()
{

Secunderabad Railway Station - 7801004784 22/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
win2=open("","window2")
win2.document.open("text/plain")
win2.document.writeln("Title: "+document.title)
win2.document.writeln("Links: "+document.links.length)
win2.document.writeln("Anchors: "+document.anchors.length)
win2.document.writeln("Forms: "+document.forms.length)
win2.document.writeln("Images: "+document.images.length)
win2.document.writeln("Applets: "+document.applets.length)
win2.document.writeln("Embeds: "+document.embeds.length)
win2.document.close()

}
</script>
<applet></applet>
</head>
<body bgcolor="lightblue">
<a href="dateobject.html">
<img src="y:\cur-swetha\swetha\falls.jpg" height=100 width=100></a>
<form>
<input type="button" name="help" value="Help" onclick="create()">
</form>
<form>
</form>
<script language="javascript">
setTimeout("create()",11000)

</script>
</body>
</html>
Navigator Object
The navigator object provides information about the type and version of the browser that is
used to run a script.
Property:
appCodeName
AppMinorVersion
appName
appVersion
browserLanguage
connectionSpeed
cookieEnabled
cpuClass
onLine
Language
mimeTypes
platform
userAgent
userLanguage
userprofile

Example:
<html>
<head>
<title>Navigator Object</title>
<script language="javascript">

function displayExplorerProperties()

Secunderabad Railway Station - 7801004784 23/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
{
with(document)
{

write("<b>AppName: </b>")
writeln(navigator.appName+"<br>")
write("<b>AppVersion: </b>")
writeln(navigator.appVersion+"<br>")
write("<b>AppCodeName: </b>")
writeln(navigator.appCodeName+"<br>")
write("<b>PlatForm: </b>")
writeln(navigator.platform+"<br>")
write("<b>UserAgent: </b>")
writeln(navigator.userAgent+"<br>")
write("<b>Language: </b>")
writeln(navigator.language+"<br>")
}
}
displayExplorerProperties();
</script>
<body bgcolor="lightblue">

</body>
</html>
The screen Object
The screen object is an object that is property of the window object. It provides information about the dimensions
and color depth of the user’s screen.
Example
<html>
<head>
<title>Screen Object</title>
<script language="JavaScript">
function displayScreenProperties()
{
with(document)
{
write("<b>Height:</b>");
writeln(screen.height+"<br>");
write("<b>Width:</b>");
writeln(screen.width+"<br>");
write("<b>ColorDepth:</b>");
writeln(screen.colorDepth+"<br>");
}
}
displayScreenProperties();
</script>
</head>
<body>
welcome
<script language="javascript">
displayScreenProperties();
</script>
</body>
</html>

The form Object

Secunderabad Railway Station - 7801004784 24/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
JavaScript provides the form object to enable the scripts to interact with and exercise control over HTML forms.
The form object is accessed as a property of the document object. Browser creates a unique form object for every
form that is contained in a document. These objects can be accessed via the document.forms[] array.

Property
Action
Button
Checkbox
Elements
fileUpload
Hidden
Length
Password
Radio
Reset
Select

Example:
<html>
<head>
<form><tile>Multiform DocumentExample</title>
<script language=”JavaScript”>
Function display()
{
win2=open(“”,”window2”)
win2.document.open(“text/plain”)
win2.document.writeln(“This document has”+document.forms.length+” forms.”)
for(i=0;i<document.forms.length;++i)
{
win2.document.writeln(“Form”+i+” has “+document.forms[i].elements.length+” elements.”)
for(j=0;j<document.forms[i].elements.length;++j)
{
win2.document.writeln(j+1)” A” + document.forms[i].elements[j].type+” element.”)
}
}
win2.document.close()
return false
}
</script>
</head>
<body>
<h1>Multiform Document Example</h1>
<form action=”Nothing” onSubmit=”return display()”>
<h2>Form 1</h2>
<p>Text Field:<input type=text name=t1 value=”Smaple text”></p>
<p>Passwordfield<inp[ut type=”password” name=t2 ></p>
<input type=submit name=f1 value=submit>
<input type=reset name=”re”>
</form>
<hr>
<form>
<h2>Form</h2>
<p><input type=checkbox name=chk1 value=”1” checked>check me!</p>
<p><input type=checkbox name=chk1 value=”2”> No. check me!</p>
<p><input type=checkbox name=chk1 value=”3”>Check all of us!</p>
</form>
Secunderabad Railway Station - 7801004784 25/29
Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<hr>
</body>
</html>

Math Object
The Math Object provides a standard library of mathematical constants and functions. The constants are defined
as properties of Math. The functions are defined as methods of Math. Specific instances of Math are not created
because Math is a built in object and not an object type.
Example:
<html>
<head>
<title>Object Array</title>
</head>
<body bgcolor="lightblue">
<script language="javascript">
document.write("<br><br>"+Math.PI)
document.write("<br><br>"+Math.sqrt(25))
document.write("<br><br>"+Math.round(2.714))
document.write("<br><br>"+Math.round(Math.random()*100))
document.write("<br><br>"+Math.random())
document.write("<br><br>"+Math.pow(2,3))
document.write("<br><br>"+Math.min(100,1000))
document.write("<br><br>"+Math.max(100,1000))
</script>
</body>
</html>

Date Object
The Date Object type provides a common set of methods for working with dates and times.
Methods Constructor
getDate() Date()
setDate() Date(Datestring)
GetDay() Date(milliseconds)
getHours() Date(year, month, day,hours, minutes, seconds,
millseconds)
setHours()
getMilliseconds()
setMilliseconds()
getMinutes()
setMinutes()
getMonth()
setMonth()
Getseconds()
setSeconds()
getTime(), setTime()
getYear(), setYear()
toLocalString(), toString(), valueOf(),
Example:
<html><head><title>Using the Date Object Type</title></head>
<body>
<h1>Using the Date Object Type</h1>
<script language=”javaScript”>
currentDate=new Date()
with(currentDate)
{
Document.write(“Date:”+getMonth()+”/”+getDate()+”/”+getYear()+”<br>”)

Secunderabad Railway Station - 7801004784 26/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
Document.write(“Time:”+getHours()+”:”+getMinutes()+”:”+getSeconds())
}
</script>
</body>
</html>

String Object
The String object type allows strings to be accessed as objects. It supports the length and prototype properties.
The length property identifies the strings length in characters.

Methods Methods
charAt(index) charCodeAt(index)
fromCharCode(codes) indexOf(pattern,startindex)
lastIndexOf(pattern) lastIndexOf(pattern, startindex)
Split(separator) Substring(startindex)
Substring(startindex,endindex) toLowerCase()
toString() toUpperCase()
valueOf()
Example:

<html>
<head>
<title>Object Array</title>
</head>
<body bgcolor="lightblue">
<script language="javascript">
function display(text)
{
document.write("<br><br>"+text)
}
s=new String("abcdefghde")
display(s)
display('charAt(1)= '+s.charAt(1))
display('charCodeAt(1)= '+s.charCodeAt(1))
display('indexOf("de")= '+s.indexOf("de"))
display('lastIndexOf("de")= '+s.lastIndexOf("de"))
display('substring(2,6)= '+s.substring(2,6))
display('toLowerCase()= '+s.toLowerCase())
display('toUpperCase()= '+s.toUpperCase())
</script>
</body>
</html>

Exercise:

1. Write a JavaScript program to find your age using date object


2. Write a Java Script program to find the reverse of a given string
3. Write a JavaScript program to find a given string is Palindrome
4. Write a JavaScript program to display an advertisement one by one automatically in a particular interval
time

Cookies
Hidden form fields were introduced to enable CGI programs to maintain state information about Web browsers.
However, hidden fields do not allow state information to be maintained in a persistent manner. That is hidden
fields can only used within a single browser session.

Secunderabad Railway Station - 7801004784 27/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
A cookie consists of information sent by a server-side program in response to a URL request by the browser. The
browser stores the information in the local cookie file according to the URL of the CGI program sending the
cookie.
Cookie provides CGI programs with the capability to store information on browsers. Browsers return this
information to CGI programs when they request the URL of the CGI program.
Cookies are obviously more powerful than hidden form fields. Since cookies can persist between browsers
sessions, they may be used to store permanent user data, such as identification information and preferences, as
well as state information.
A cookie is created when a CGI program includes a Set-Cookie header as part of an HTTP response. This
response is generated when a browser requests the URL of the CGI program. The syntax of the Set-Cookie
header is:

Syntax:
Set-Cookie: NAME=VALUE[; expires=DATE][;path=PATH][;domain=DOMAIN_NAME][;secure]

The NAME=VALUE field is required. The other field are optional

The NAME=VALUE field:


This field contains the essential data being stored in a cookie.

The expires=DATE field:

This field specifies the expiration date of a cookie. If it is omitted, the cookie expires at the end of the current
browser session. The date is specified in the following format:

Weekday, dd-mon-yy hh:mm:ss GMT

The domain=DOMAIN_NAME field:


When a cookie is stored in the local file system, it is organized by the URL of the CGI program that sent the
cookie. The domain field is used to specify a more general domain name to which the cookie should apply.

The path=PATH field:


This field is used to specify a more general path for the URL associated with a cookie.

The secure Field:

I f the secure field is specified, and then a cookie is only sent over a secure communication channel.

Example:

<html>
<head><title>Cookie Test</title>
<script language=”JavaScript”>
Function udatecookie()
{
Document.cookie=document.form1.cookie.value
Location.reload(true)
}
</script>
</head>
<body>
<script language=”javaScript”>
Document.write(“your current cookie value is:”+document.cookie)
</script>
<form action=” “ name=”form1”>
<p>Enter new Cookie:<input type=text size=60 name=”cookie”>
</p>

Secunderabad Railway Station - 7801004784 28/29


Interface Informatics Pvt.Ltd ISO 9001: 2008 JavaScript Reference Book
<input type=button name=setCookie value=set cookie onClick=”updateCookie()”>
</form>
</body>
</html>
Exercise:
1. Write a JavaScript program to find how many hours a user used a particular web site or web page
2. Write a JavaScript program to find how many users visit a particular web page.

Secunderabad Railway Station - 7801004784 29/29

Vous aimerez peut-être aussi