[go: up one dir, main page]

0% found this document useful (0 votes)
83 views75 pages

Java Script: Introduction To Javascript

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 75

JAVA SCRIPT

Introduction to JavaScript

JavaScript is used in Web pages to improve the design, validate forms, and much more.
JavaScript was developed by Netscape and it is the most popular scripting language on the internet. It is
a lightweight interpreted programming language initially called LiveScript, which quickly evolved into
what is now JavaScript.

JavaScript is an untyped language, which means that variables do not have to a type specified.
JavaScript works in all major browsers that are version 3.0 or higher.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages.


 JavaScript is a scripting language - and is a lightweight programming language.
 A JavaScript is usually embedded directly in HTML pages.
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
 JavaScript is supported by all major browsers, like Netscape and Internet Explorer

Whether JavaScript and Java the Same?

JavaScript Java
JavaScript are interpreted by the browser. Java Programs are compiled on the server but run
on the client. Otherwise called Compiler Language
JavaScript is objected-based. There are no classes. Java is Object-oriented. It employs classes and
There is no inheritance. inheritance.
Variable data types not declared (loose typing) Variable data type must be declared (Strong
Dynamic Binding. Object references checked at typing) Static Binding. Object references must exist
runtime. at compile time.
Script Limited to browser functions Stand-alone Applications.
JavaScript is integrated and embedded in HTML Java is compiled into “applets” that are accessed
from HTML pages
Created by Netscape Corporation Created by Sun Microsystems.

Purpose of Scripting

1. Form Validation
2. Page embellishment, including rollover buttons and animation.
3. Dynamic Page generation
4. Making Pages interactive
Client-side JavaScript

Embedded in HTML on client side and the output result is client-side JavaScript. The two
browsers, Netscape Navigator(version 3.0 and above) and Internet Explorer(version 3.0 and above).
Support client-side JavaScript.

Server-Side JavaScript

Server side JavaScript environment allows you to use scripts to build web based applications
that are controlled by the Web Server. It provides an alternative of CGI(Common Gateway Interface) is
directly within HTML pages intermixed with web content.

Whenever a document containing server-side JavaScript code is requested by the client, the
server executes the script or scripts contained in the document and send the resulting document to the
requester.

Server-side JavaScript communicating with client accessing files on the server and connecting to
the Databases.

Ex: ASP(Active Server Page) from Microsoft, JSP(Java Server Page) from Sun Microsystems.

How to put a JavaScript into an HTML Page?

<script type=”text/javascript”>
(or)
<script language=”JavaScript”>

We can apply the script in both HEAD and BODY Tag. If we apply script in HEAD tag we can executing a
script by calling a function. When we apply script to the BODY tag it shows the content of the web page.

The JavaScript command for writing some output to a page is document.write.

document.write(“String”)

Example Program (Script in HEAD Tag)

<html>

<head>

<title>First</title>

<script type="text/javascript">

function display()
{

document.write("Welcome")

</script>

</head>

<body onload=display()>

</body>

</html>

Example Program(Script in BODY Tag)

<html>

<head>

<title>Second</title>

</head>

<body>

<script type="text/javascript">

document.write("Welcome")

</script>

</body>

</html>

How to Run an External JavaScript

To simplify this you can write a script in an external file, and save it with a .js file extension.

Example(test.js)

document.write(“This script is external”)

ExternalJS.html

<html>
<head>

<title>External JavaScript</title>

</head>

<body>

<script src="test.js"></script>

</body>

</html>

Statements

Statements are simply commands that perform a certain purpose. Several statements are built
into JavaScript; these are used to test variables, control the flow of the program, and perform actions.

Ex: document.write() is a statement

Comments

The comments are ignored by the JavaScript interpreter:

1) Single line comment //


2) Multiline comment /* */

Values

The value of each variable depends on the context in which it is assigned types.

var x=7 [x is an integer by assigning the value 7]

var z=”19” [z are strings by assigning the value 19]

The initial value of the property is usually specified by the VALUE attribute of FORM element.

Ex:

today=new date();

document.myform.date.value=today;

Literal:

Literals are numbers or strings used to represent fixed values in JavaScript. They are don’t
change during the execution of your scripts.
Variables

Variables are named containers that can hold a value. A variable value can change during the
script.

Rules

1) Variable names are case sensitive.


2) They must begin with a letter or the underscore(_). Variable names can include letters of the
alphabets, both upper and lowercase, digits(0-9) and underscore(_).
3) Variable name can’t include spaces or any other punctuation character.
4) Variable name is not a reserved words.

Declare a variable

To declare a variable in JavaScript var keyword is used.


var variable_name=value;

Ex: var i=10;

You can also create a variable without using var keyword.

variable_name=value;

Ex: i=10;

Assign a value to the variable

Assignment operator(=) is used.

Ex:

var wheels=18;

or you can assign by using untyped variables like this:

wheels=18;

Datatypes

5 Major implicit data types in JavaScript.

1) Numbers – both integers and floating-point numbers

2) Boolean – true or false


3) Strings – consists of one or more characters of text

4) null – This is the value of an undefined variable

5) non-atomic – JavaScript element, such as function or object

Scope of the variable

The scope of a variable refers to the areas within a program where a variable can be referened:

1) Local scope – A variable declared within a function with the var keyword is local to that
function. Other functions can’t access it. Variables used to store the function’s parameters are
also local to that function.
2) Global scope – A variable declared outside of a function, or without var keyword in a function, is
global; all JavaScript statements in the current HTML or script file can access the value.

Integers

An integer is simply a number that does not include a decimal. Integers in JavaScript can be only
positive numbers. You can use an integer as a literal in JavaScript simply by including the number.

JavaScript considers any number without a leading zero to be a decimal(base 10) number. You
can also use data in hexadecimal(base 16) and octal(base 8).

 Decimal: no leading zero(ex: 57, 5000)


 Hexadecimal: prefix with 0x(0x56,0xFE)
 Octal: Leading 0(045,013)

Floating-point numbers

Unlike integers, floating-point values can be either positive or negative. Any number without a
negative sign is assumed to be positive.

To use the exponent notation, the letter E can be used.

 1E6: One million (1,000,000)


 1.5E9: 1.5 billion (1,500,000,000)
 25E-2: One-quarter(.25)
 1E-6: One-millionth (.000001)
 4.56E5: 456,000

Boolean Values

Boolean values are the simplest data type. They can contain one of two values: true or false.
Because they can represent an on/off or 1/0 state, these are sometimes called binary values.
Boolean values are most commonly used as flags; variables that include whether a condition is
true or not.

Strings

Another important type of value in a JavaScript program is a string. Strings are simply groups of
characters. You can enclose a string enclosing them in double or single quotation marks.

 “This is a string.”
 ‘A’
 ’25 pounds’
 “200”

Special Characters

Along with alphanumeric characters, you can use a variety of special characters in JavaScript
strings. These include carriage returns, tabs and other nonprintable characters. To use a special
character we use backslash(\) followed by the code for the character.

 \a: Alert(bell) character (produces a bell sound)


 \b: Backspace character(moves the cursor back one character)
 \f: Form-feed character (indicates a new page on a printer)
 \n: New line character(indicates a new line of text)
 \r: Carriage return character(moves the cursor to the beginning of the line)
 \t: Tab character(advances the cursor to the next tab stop)

Creating an array

JavaScript does not support arrays a variables. Instead, they are handled as objects. You can
create an array by using the Array Object.

Ex: scores=new Array(20);

Once you define the array, you can access its elements by using brackets [ ] to indicate the
index.

Ex: scores[0]=50;

scores[1]=98;

Unicode

In the string object’s characters processing methods, it include the charCodeAt() method, which
return the Unicode value of the character at the specified position. If there is no character at that index,
it return NaN(not a number).
Expression

By combining the variables and literal values to form a complex expression. The tools you use to
create an expression are operators.

An expression is a “phrase” of JavaScript that a JavaScript interpreter can evaluate to produce a


value.

Operators
-> Operator is a symbol that is used to perform the Mathematical and Logical operation.
Types
1) Unary Operators

2) Binary Operators

1) Unary Operators
-> It hold only one operand(variable) to perform the operation.
Types

(i) Pre-increment/decrement operators


-> It first increment/decrement the variable value itself by one then perform the operation.

++variable;
--variable;

(ii) Post-increment/decrement operators


-> It first perform the operation then increment/decrement the variable value itself by one.
variable++;
variable--;

Program

<html>

<head>

<title>Unary Operators</title>

</head>

<body>

<script type="text/javascript">

a=10;
document.write("++a="+(++a)+"<br>");

document.write("--a="+(--a)+"<br>");

document.write("a++="+(a++)+"<br>");

document.write("a--="+(a--)+"<br>");

document.write("a="+a);

</script>

</body>

</html>

(2) Binary Operators

-> It hold two or more operands (variables) to perform the operation.

Types

(i) Arithmetic Operators(+,-,*,/,%)


(ii) Logical Operators(&&-AND,||-OR,!-NOT)
(iii) Relational (or) Comparison operators(<,>,<=,>=,==,!=)
(iv) Bitwise Operators(&-Bitwise AND,|-Bitwise OR, ^-Bitwise XOR)
(v) Shift Operators(<<, >>)
(vi) Assignment operator(=)
(vii) Short-hand assignment operators(+=,-=,*=,/=,%=)
(viii) Ternary (or) Conditional Operator (condition)?True_value:False_value;

(i) Arithmetic Operators(+,-,*,/,%)

Program

<html>

<head>

<title>Binary Operators</title>

</head>

<body>

<script type="text/javascript">

a=10,b=6;
document.write("Addition="+(a+b)+"<br>");

document.write("Subtraction="+(a-b)+"<br>");

document.write("Multiplication="+(a*b)+"<br>");

document.write("Division="+(a/b)+"<br>");

document.write("Modulo Division="+(a%b)+"<br>");

</script>

</body>

</html>

(ii) Logical Operators(&&-AND,||-OR,!-NOT)

Program

<html>

<head>

<title>Logical Operators</title>

</head>

<body>

<script type="text/javascript">

a=10,b=20,c=5;

res=(a>b&&a>c);

document.write("result="+res+"<br>");

res=(a>b||a>c);

document.write("result="+res+"<br>");

res=!(a>b);

document.write("result="+res+"<br>");

</script>
</body>

</html>

(iii) Relational (or) Comparison operators(<,>,<=,>=,==,!=)

Program

<html>
<head>
<title>Relational Operators</title>
</head>
<body>
<script type="text/javascript">
a=10,b=20;
c=a>b;
document.write("c="+c+"<br>");
c=a<b;
document.write("c="+c+"<br>");
c=a>=b;
document.write("c="+c+"<br>");
c=a<=b;
document.write("c="+c+"<br>");
c=a==b;
document.write("c="+c+"<br>");
c=a!=b;
document.write("c="+c);
</script>
</body>

</html>

(iv) Bitwise Operators(&-Bitwise AND,|-Bitwise OR, ^-Bitwise XOR)

-> It is used for the manipulation of bits(0s and 1s)

Bitwise AND(&) Bitwise OR(|) Bitwise XOR(^)

Input Output Input Output Input Output


A B A&B A B A|B A B A^B
0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0
Program

<html>

<head>

<title>Bitwise Operators</title>

</head>

<body>

<script type="text/javascript">

a=5,b=8,c=0;
c=a&b;
document.write("c="+c+"<br>");
c=a|b;
document.write("c="+c+"<br>");
c=a^b;
document.write("c="+c+"<br>");
</script>

</body>

</html>

(v) Shift Operators(<<,>>)

-> It shift the binary digits left and right sides.

<< - left shift >> - right shift

Program

<html>

<head>

<title>Bitwise Operators</title>

</head>

<body>

<script type="text/javascript">
a=5;

document.write("a left shift 2 times:"+(a<<2)+"<br>");

document.write("a right shift 2 times:"+(a>>2)+"<br>");


</script>

</body>

</html>

Formula
(i) Left Shift
Value*2n
(ii) Right Shift
Value*2-n
n – number of shift
(vi) Assignment Operator(=)
-> It is used to assign a value to the variable
variable=value (or) var variable=value;

(vii) Short-hand assignment operators (+=,-=,*=,/=,%=)

Program

<html>

<head>

<title>ShortHand Assignment Operators</title>

</head>

<body>

<script type="text/javascript">

a=10,b=5;

a+=b;

document.write("a="+a+"<br>");

a-=b;

document.write("a="+a+"<br>");
a*=b;

document.write("a="+a+"<br>");

a/=b;

document.write("a="+a+"<br>");

a%=b;

document.write("a="+a+"<br>");
</script>

</body>

</html>

(viii) Ternary(or)conditional operator

(condition)?True_value:False_value;

Program

<html>

<head>

<title>Ternary Operator</title>

</head>

<body>

<script type="text/javascript">

a=100,b=15,big=0;

big=(a>b)?a:b;

document.write("big="+big);

</script>

</body>

</html>

(ix) Typeof Operator


The typeof operator returns the type of data that its operand currently holds. This is especially
useful for determining if a variable has been defined.

Example:

Typeof 33 - It returns the string “number”

Typeof “Astring” - It returns the string “string”

Typeof true - It returns the string “Boolean”

Program

<html>

<head>

<title>Typeof Operator</title>

</head>

<body>

<script type="text/javascript">

a=100;

document.write("Type of a="+typeof(a)+"<br>");

msg="Have a Nice Day";

document.write("Type of msg="+typeof(msg)+"<br>");

result=(10>20);

document.write("Type of result="+typeof(result));

</script>

</body>

</html>

Order of Precedence

The order of precedence determines the order in which the browser applies operators to
operands when evaluating an expression.
The order of precedence, from highest(perform first) to lower(perform last) is

 Bitwise negate, logical not, negate, post-decrement, post-increment, pre-decrement, pre-


increment
 Multiplication, Division, modulo
 Addition, concatenation, subtraction
 Shift left, sign-propagating shift-right, zero-fill shift right Greater than, Greater than or equal,
Less than, Less than or equal
 Equality, inequality
 Bitwise AND
 Bitwise EXCLUSIVE-OR
 Bitwise OR
 Logical AND
 Logical OR
 Conditional
 Assignment, Shorthand Assignment

Conditional Statements

Conditional Statements in JavaScript are used to perform different actions based on different
conditions. In JavaScript we have five conditional statements:

1. Simple if
2. if…else
3. if…else if…else
4. nested if
5. switch case
1. Simple if

-> It test the condition if it is true it execute a block of code. Otherwise it is skipped.
if(condition)
{
Statement(s);
}
if – keyword

Program

<html>

<head>

<title>Simple If</title>

</head>
<body>

<script type="text/javascript">

var n;

n=parseInt(prompt("Enter the number:"))

if(n<0)

document.write('The number is Negative')

</script>

</body>

</html>

(ii) if…else

-> It test the condition if it is true the True-Block Statement(s) are executed. Otherwise the else part ie
the False-Block Statement(s) are executed.

if(condition)
{
True-Block Statement(s);
}
else
{
False-Block Statement(s);
}

if, else - keywords

Program

<html>

<head>

<title>If Else</title>

</head>

<body>

<script type="text/javascript">

var n;
n=parseInt(prompt("Enter the number:",0,"input"))

if(n<0)

document.write('Number is Negative')

else

document.write('Number is Positive')

</script>

</body>

</html>

(iii) if…else if…else (or) if…else if…else ladder


-> It test the condition-1 if it is true it execute True Block Statement(s)-1 are executed. otherwise it test
another condition and so on. When all the condition become false it execute else part ie false block
statement(s).

if(condition-1)
{
True-Block Statement(s)-1;
}
else if(condition-2)
{
True-Block Statement(s)-2;
}
.
.
.
else
{
False-Block Statement(s);
}
Program

<html>

<head>

<title>If Else If Else</title>

</head>

<body>

<script type="text/javascript">
var a,b,c;

a=parseInt(prompt("Enter the a value:",0))

b=parseInt(prompt("Enter the b value:",0))

c=parseInt(prompt("Enter the c value:",0))

if(a>b&&a>c)

document.write('A is biggest')

else if(b>c)

document.write('B is biggest')

else

document.write('C is biggest')

</script>

</body>

</html>

(iv) nested if
-> An if consists of another if…else if…else ladder it is called nested if.
if(Main condition)
{
if(condition-1)
{
True-Block Statement(s)-1;
}
else if(condition-2)
{
True-Block Statement(s)-2;
}
.
.
else if(condition-n)
{
True-Block Statement(s)-n;
}
else
{
False-Block Statement(s);
}
}
Program

<html>

<head>

<title>Nested If</title>

</head>

<body>

<script type="text/javascript">

var a,b,c;

a=parseInt(prompt("Enter the a value:",0))

b=parseInt(prompt("Enter the b value:",0))

c=parseInt(prompt("Enter the c value:",0))

if(a>b)

if(a>c)

document.write('A is biggest')

else

document.write('C is biggest')

else if(b>c)

document.write('B is biggest')

else

{
document.write('C is biggest')

</script>

</body>

</html>

(v) Switch case


-> Switch case is the powerful branching statements compared with if…else if…else because of its speed
up of operation.
-> switch case expression test with the case label. When the corresponding case label is matched the
control go to that block and execute a set of statements and terminate using break keyword.
-> When all the case label is does not match the default block i.e the invalid statement(s) are executed.

switch(expression)
{
case label-1:
Statement(s)-1;
break;
case label-2:
Statement(s)-2;
break;
.
.
.
case label-n:
Statement(s)-n;
break;
default:
Invalid Statement(s)-1;
break;
}

switch, case, break, default – keywords

case labels are integer, character constants

break – it is used to immediately terminate the switch case.

Program

<html>

<head>
<title>Switch Case</title>

</head>

<body>

<script type="text/javascript">

day=parseInt(prompt('Enter the weekday number:'))

switch(day)

case 1:

document.write('Sunday')

break

case 2:

document.write('Monday')

break

case 3:

document.write('Tuesday')

break

case 4:

document.write('Wednesday')

break

case 5:

document.write('Thursday')

break

case 6:

document.write('Friday')

break
case 7:

document.write('Saturday')

break

default:

document.write('Invalid Weekday Number')

</script>

</body>

</html>

Looping or Iterative Statements

Looping statements in JavaScript are used to execute the same block of statement for a
specified number of times.

In JavaScript we have the following looping statements:

1. while
2. do…while
3. for

1. while

The while statement will execute a block of code while a condition is true.

while(condition)
{
Code to be executed
}

Program-1

<html>

<head>

<title>While Loop</title>
</head>

<body>

<script type="text/javascript">

n=parseInt(prompt("Enter the number of times your name printed:"))

i=1

while(i<=n)

document.write("CSC"+"<br>")

i++

</script>

</body>

</html>

Program-2

<html>

<head>

<title>While Loop</title>

</head>

<body>

<script type="text/javascript">

n=parseInt(prompt("Enter the value to be printed:"))

i=1

while(i<=n)

document.write(i+"<br>")
i++

</script>

</body>

</html>

2. do…while

The do…while statement will execute a block of code once, and then it will repeat the loop while
a condition is true.

do
{
Code to be executed
}while(condition);

Program

<html>

<head>

<title>Do While Loop</title>

</head>

<body>

<script type="text/javascript">

n=parseInt(prompt("Enter the value to be printed:"))

i=1

do

document.write(i+"<br>")

i++
}while(i<=n);

</script>

</body>

</html>

4. for loop
The for statement will execute a block of code a specified number of times

for(initialization; condition; increment/decrement part)


{
Code to be executed
}

Program

<html>

<head>

<title>For Loop</title>

</head>

<body>

<script language="JavaScript">

document.write("<h2> Table of Factorials</h2>");

for(i=1,fact=1;i<=10;i++,fact*=i)

document.write(i+"!="+fact);

document.write("<br>");

</script>

</body>

</html>
The for…in Construct

The for..in loop is not as flexible as ordinary for or while loops; instead, it is specifically designed
to perform an operation on each property of an object.

for(variable in array|object)
{
Code to be executed
}

Program

<html>

<head>

<title>For Each Loop</title>

</head>

<body>

<script language="JavaScript">

document.write("<h2> For Each Loop Example</h2>");

players=new Array()

players[0]="Sachin"

players[1]="Sehwag"

players[2]="Dhoni"

players[3]="Rohit"

players[4]="Kohli"

players[5]="Dawan"

for(i in players)

document.write(players[i]);

document.write("<br>");
}

</script>

</body>

</html>

The break Statement

There is one way out of an infinite loop. The break statement can be used during a loop to exit
the loop immediately and continue with the first statement after the loop:

Program

<html>

<head>

<title>Break Keyword</title>

</head>

<body>

<script language="JavaScript">

for(i=0;i<10;i++)

if(i==5)

break;

document.write(i);

document.write("<br>");

</script>

</body>

</html>

The continue statement


The continue statement skips the rest of the loop, but unlike break, it continues with the next
iteration of the loop.

Program

<html>

<head>

<title>Continue Keyword</title>

</head>

<body>

<script language="JavaScript">

for(i=0;i<10;i++)

if(i%2!=0)

continue;

document.write(i);

document.write("<br>");

</script>

</body>

</html>

With Statement

The with statement is used to avoid repeatedly specifying the object reference when accessing
properties or methods of that object.
with(object)
{
Statements
}
Program

<html>
<head>

<title>With Statement</title>

</head>

<body>

<script language="JavaScript">

with(document)

write("hello");

write("<br>The title of this window is:\""+title+"\" ");

</script>

</body>

</html>

Functions:
A function is a reusable code-block that will be executed by an event, or when the function is
called.
A function contains some code that will be executed by an event or a call to that function. A
function is a set of statements. You can reuse functions within the same script, or in other documents.
You define functions at the beginning of a file (in the head section), and call them later in the document.
How to Define a function
To create a function you define its name, any values as(“arguments”), and some statements.
function myfunction(argument1,argument2,…)
{
Some statements
}

A Function with no arguments must include the parenthesis:


function myfunction()
{
Some statements
}

Arguments are variables used in the function. The variable values are passed on by the function
call.
By placing functions in the head section of the document, you make sure that all the code in the
function has been loaded before the function is called.

Some functions return a value to the calling expression

How to call a function

A function is not executed before it is called. You can call a function containing arguments:

myfunction(argument1,argument2,etc)

Or without arguments:
myfunction()

Example Program

<html>

<head>

<title>Function</title>

<script type="text/javascript">

function greet(who)

alert("Greeting from "+who);

</script>

</head>

<body>

<script type="text/javascript">

greet("CSC");

</script>

</body>
</html>

The return statement

Functions that will return a result must use the “return” statement. This statement specifies the
value which will be returned to where the function was called from. Say you have a function that returns
the sum of two numbers:
function total(a,b)
{
result=a+b
return result
}

When you call this function you must send two arguments with it:

sum=total(2,3)

Program

<html>

<head>

<title>Returning Function</title>

<script type="text/javascript">

function total(a,b)

result=a+b

return result

</script>

</head>

<body>

<script type="text/javascript">

sum=total(2,3)

document.write("Sum of two numbers="+sum)


</script>

</body>

</html>

The arguments [] array

The arguments [] property of a function object refers to an array that contains the complete set
of argument values passed to the function. JavaScript allows any number of argument values to be
passed to any function with the number of argument names that appear in the function definition.

The arguments.length property count the number of arguments that we are passed in the
function.

Program

<html>

<head>

<title>Arguments Array</title>

<script type="text/javascript">

function f(x,y,z)

if(f.arguments.length!=3)

alert("Function f called with "+f.arguments.length+" arguments, but it expects 3


arguments.");

return null;

</script>

</head>

<body>

<script type="text/javascript">

f(2,3)

</script>
</body>

</html>

Predefined Function (Built-in Functions)

The JavaScript provides a number of built-in functions that are part of the language.

For example, the parseInt() function converts a string to an integer, and the Math.sin() function
computes the sine of a number.

JavaScript Objects

Functions are used to proved a uniform method for organizing code, Objects serve the same
purpose for data. Objects provide the ability to hold multiple values, so that a group of related data
elements can be associated with one another.

An object is a custom data type that can combine data with functions to act upon it. The data
items in an object are its properties, and the functions are its methods.

Using Object Properties

The bits of data stored in an object are called properties of the object. Each object can have one
or more properties or attributes. Properties can be numbers, strings, or even other objects. Each
property has a name associated with it, which you must use to refer to that property.

To illustrate object properties, let us take the example the String object. Any variable that
contains a string in JavaScript is actually a String object. The String object has a single property called
length (built-in object), which indicates the current length of the string. You can use two different types
of notation to refer to an object’s property.

The first and most common method is to separate the object name and property name with a
period (dot operator(.)).

For example, the following statement sets the variable len to the length of the address string
variable:
len=address.length;

Object can also include methods. There are functions that work with the objects data. For
example,
var StringVar=new String(“this is a string”);
var x=StringVar.length;
StringVar=StringVar.toUpperCase();

After executing this code, StringVar is a new variable with the value of “this is a string”.
The x variable is set of the length of the StringVar, it produce 16. Length is a property of String object.

The UpperCase() method converts all of the string to upper case. i.e “THIS IS A STRING”.

Creating New Objects with Constructors

Object and arrays must be created with new operator. The new operator is to create a new
instance of an object or an array.

Syntax:

O=new Object();

Since objects are made up of methods(functions) and parameters(variables), the newly created
object “O” in this case has all of the same methods and parameters of the original object. The
parameters will all be set to their default value.

A constructor is a JavaScript function with three special features:

 It is invoked through the new operator


 It is passed a reference to a newly created, “empty” object as the value of the special this
keyword, and it is responsible for performing appropriate initialization for that new object
 It should not return a value; if it uses the return statement, it should do so without a value to be
returned

Example Program: A Rectangle Object Constructor Function

<html>

<head>

<title>Constructor</title>

<script type="text/javascript">

function Rectangle(w,h)

this.width=w;

this.height=h;

document.write("Area of Rectangle="+this.width*this.height+"<br>");

}
</script>

</head>

<body>

<script type="text/javascript">

rect1=new Rectangle(2,4);

rect2=new Rectangle(8.5,11);

</script>

</body>

</html>

The Constructor performs its initialization on the object referred to by the this keyword.

A constructor will generally perform initialization based on the argument values that are passed to it.
Some constructors may also initialize other properties of a new object

The new keyword

The new operator actually creating an instance of an object class. Any variable you create with
the new keyword is an instance of that object. The object definition itself is referred to as the object
class, or the object type.

With some built-in objects, such as the String object, you don’t need to use the new keyword;
you simply define a string variable, and JavaScript creates a String object automatically.

The this keyword

It is simply shorthand for “the current object.” This is usually used in object definitions, where it
refers to the object being defined, and in method definitions, where it refers to the object the method is
acting on.

Example Program

<html>

<head>

<title>Method to String Object</title>

</head>

<body>
<script language="JavaScript">

function mth(level)

html="H"+level;

text=this.toString();

start="<"+html+">";

stop="</"+html+">";

return start+text+stop;

String.prototype.heading=mth;

document.write("This is a test".heading(1));

</script>

</body>

</html>

Built-In Objects

JavaScript includes several built-in objects. They are not part of the object hierarchy, and they
do not represent any part of a web page. They are used for programming functions. The built-in
functions as follows:

 Array objects to store numbered variables.


 String objects to manipulate strings of characters
 Date objects enable you to store and work with dates
 Math object includes methods and properties for mathematical functions.
 Navigator object stores information about the user’s browser and its capabilities

Array Object

An Array object is used to store a set of values in a single variable name. Each value is an
element of the array and has an associated index number.

You can refer to a particular element in the array by using the name of the array and the index
number. The index number starts at zero.
You create an instance of the Array object with the “new” keyword.

var family_names=new Array(5)

The expected number of elements goes inside the parentheses, in this case 5.

You assign data to each of the elements in the array like this:
family_names[0]=”Tony”
family_names[1]=”Jani”
family_names[2]=”Gajini”
family_names[3]=”Bhaski”
family_names[4]=”Kai”

And the data can be retrieved from any element by using the index of the particular array element you
want. Like this:

mother=family_names[0]
father=family_names[1]

The Array object’s methods are described below table

Methods Explanation
length – property Returns the number of elements in an array. This
property is assigned a value when an array is
created
concat() Returns an array concatenated of two arrays
join() Returns a string of all the elements of an array
concatenated together
reverse() Returns the array reversed
slice() Returns a specified part of the array
sort() Returns a sorted array

Example Program

<html>

<head>

<title>Array Object</title>

</head>

<body>

<script language="JavaScript">
var family_names=new Array();

family_names[0]="Tony";

family_names[1]="Jani";

family_names[2]="Gajini";

family_names[3]="Bhaski";

family_names[4]="Kai";

document.write("Family Names:<p>");

for(var i=0;i<family_names.length;i++)

document.write(i+1+"."+family_names[i]+"<br>");

var joint_family=new Array();

joint_family[0]="Ram";

joint_family[1]="Suresh";

document.write("</p>");

document.write("Length of the Array="+family_names.length+"<br>");

document.write("Concatenation of the Array="+family_names.concat(joint_family)+"<br>");

document.write("Join of the Array="+family_names.join(joint_family)+"<br>");

document.write("Reverse the Array="+family_names.reverse()+"<br>");

document.write("Slice the Array="+family_names.slice(1,4)+"<br>");

document.write("Sorted the Array="+family_names.sort()+"<br>");

</script>

</body>

</html>
The String object

The String object is used to work with text.

Properties Explanation
length Returns the number of characters in a string

Methods Explanation
anchor() Returns a string as an anchor
big() Returns a string in big text
small() Returns a string as small text
blink() Returns a string blinking
bold() Returns a string in bold
italics() Returns a string in italic
strike() Returns a string strikethrough
charAt() Returns a character at a specified position
charCodeAt() Returns the Unicode of the character at a specified position
concat() Returns two concatenated strings
fixed() Returns a string as teletype
fontcolor() Returns a string in a specified color
fontsize() Returns a string in a specified font size
fromCharCode() Returns the character value of a Unicode
indexOf() Returns a position of the first occurrence of a specified string inside
another string. Returns -1 if it never occurs.
lastIndexOf() Returns the position of the first occurrence of a specified string inside
another string. Returns -1 if it never occurs. Note: This method starts from
right and moves left
link() Returns a string as a hyperlink
match() Similar to indexOf and lastIndexOf but this method returns the specified
string, or “null”, instead of a numeric value
replace() Replaces some specified characters with some new specified characters
search() Returns an integer if the string contains some specified characters if not it
returns -1
slice() Returns a string containing a specified character index
split() Splits a string into an array of strings
sub() Returns a string as subscript
sup() Returns a string as superscript
substr() Returns the specified characters. 14,7 returns 7 characters, from the 14th
character(starts at 0)
substring() Returns the specified characters 7,14 returns all characters from the 7th up
to but not including the 14th (starts at 0)
toLowerCase() Converts a string to lower case
toUpperCase() Converts a string to upper case
Program

<html>

<head>

<title>String Object</title>

</head>

<body>

<script language="JavaScript">

s="Computer Software College";

mylink="Click Here to view My Picture";

var my_array=new Array();

document.write("Length of s="+s.length+"<br>");

document.write("Anchor Text="+s.anchor()+"<br>");

document.write("Big Text="+s.big()+"<br>");

document.write("Small Text="+s.small()+"<br>");

document.write("Blink Text="+s.blink()+"<br>");

document.write("Bold Text="+s.bold()+"<br>");

document.write("Italic Text="+s.italics()+"<br>");

document.write("Strike Text="+s.strike()+"<br>");

document.write("Character at 10th Position="+s.charAt(10)+"<br>");

document.write("Character Code(ASCII) at 10th Position="+s.charCodeAt(10)+"<br>");

document.write("concate with 'Welcome'="+s.concat('Welcome')+"<br>");

document.write("Fixed Text(Tele type Format)="+s.fixed()+"<br>");

document.write("Font Color(Green)="+s.fontcolor('green')+"<br>");

document.write("Font size(10)="+s.fontsize(10)+"<br>");

//document.write("From Character Code Text="+s.fromCharCode('C')+"<br>");


document.write("Index of C="+s.indexOf('C')+"<br>");

document.write("Last Index of C="+s.lastIndexOf('C')+"<br>");

document.write("Link of S="+mylink.link("D:\\ANIMATION\\12g5.gif")+"<br>");

document.write("Match of C="+s.match('C')+"<br>");

document.write("Replace Soft with Hard="+s.replace('Soft','Hard')+"<br>");

document.write("Search Soft in S="+s.search('Soft')+"<br>");

document.write("Slice the String S="+s.slice(9,13)+"<br>");

document.write("Split the String S="+s.split(my_array)+"<br>");

document.write("Subscript="+s.sub()+"<br>");

document.write("Superscript="+s.sup()+"<br>");

document.write("substr="+s.substr(7,14)+"<br>");

document.write("substring="+s.substring(7,14)+"<br>");

document.write("Lower Case of s="+s.toLowerCase()+"<br>");

document.write("Upper Case of s="+s.toUpperCase()+"<br>");

</script>

</body>

</html>

The Date Object

The Date Object is used to work with dates and times. You create an instance of the Date object
with the “new” keyword.

To store the current date in a variable called “my_date”:

var my_date=new Date()

After creating an instance of the Date object, you can access all the methods of the object from
the “my_date” variable. If, for example, you want to return the date (from 1-31)

my_date.getDate()

You can also write a date inside the parentheses of the Date() object, like this:
new Date(“Month dd, yyyy hh:mm:ss”)

new Date(“Month dd, yyyy”)

new Date(yy,mm,dd,hh,mm,ss)

new Date(yy,mm,dd)

new Date(milliseconds)

Here is how you can create a Date Object for each of the ways above:

var my_date=new Date(“October 12,1988 13:14:00”)

var my_date=new Date(“October 12,1988”)

var my_date=new Date(88,09,12,13,14,00)

var my_date=new Date(88,09,12)

var my_date=new Date(500)

The Date object’s methods are described below table

Methods Explanation
Date() Returns a Date Object
getDate() Returns the date of a Date object (from 1-31)
getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday,
etc)
getMonth() Returns the month of a Date object (from 0-11, 0=January,
1=February, etc)
getFullYear() Returns the year of a Date Object (Four Digits)
getYear() Returns the year of a date object (from 0-99). Use getFullYear
instead!!
getHours() Returns the hour of a Date object (from 0-23)
getMinutes() Returns the minute of a Date object (from 0-59)
getSeconds() Returns the second of a Date object (from 0-59)
getMilliseconds() Returns the millisecond of a Date object (from 0-999)
getTimezoneOffset() Returns the time difference between user’s computer and GMT
parse() Returns a string date value that holds the number of milliseconds
since January 01 1970 00:00:00
setDate() Sets the date of the month in the Date object (from 1-31)
setMonth() Sets the month in the Date object (from 0-11,
0=January,1=February etc)
setYear() Sets the year in the Date object (00-99)
setFullYear() Sets the year in the Date object (four digits)
setHours() Sets the hour in the Date object (from 0-23)
setMinutes() Set the minute in the Date object (from 0-59)
setSeconds() Sets the second in the Date object (from 0-59)
setTime() Sets the milliseconds after 1/1-1970
toGMTString() Converts the Date object to a string, set to GMT time zone
toLocaleString() Converts the Date object to a string, set to the current time zone
toString() Converts the Date object to a string

Program

<html>

<head>

<title>Date Object</title>

</head>

<body>

<script language="JavaScript">

var my_date=new Date("January 22, 2019 10:45:00");

//var my_date=new Date("01/22/2019");

document.write("Get Date="+my_date.getDate()+"<br>");

document.write("Get Day="+my_date.getDay()+"<br>");

document.write("Get Month="+my_date.getMonth()+"<br>");

document.write("Get Year="+my_date.getYear()+"<br>");

document.write("Get Full Year="+my_date.getFullYear()+"<br>");

document.write("Get Hours="+my_date.getHours()+"<br>");

document.write("Get Minutes="+my_date.getMinutes()+"<br>");

document.write("Get Seconds="+my_date.getSeconds()+"<br>");

document.write("Get MilliSeconds="+my_date.getMilliseconds()+"<br>");

document.write("Get Time="+my_date.getTime()+"<br>");

document.write("Get Time Zone Offset="+my_date.getTimezoneOffset()+"<br>");

//document.write("Parse="+my_date.parse("22-01-2019")+"<br>");

var my_date2=new Date();


my_date2.setDate(23);

my_date2.setMonth(01);

my_date2.setYear(2019);

my_date2.setFullYear(2019);

my_date2.setHours(10);

my_date2.setMinutes(35);

my_date2.setSeconds(53);

document.write("My Date2="+my_date2+"<br>");

document.write("set Time="+my_date.setTime(19)+"<br>");

document.write("To GMTString="+my_date.toGMTString()+"<br>");

document.write("To LocaleString="+my_date.toLocaleString()+"<br>");

document.write("To String="+my_date.toString()+"<br>");

</script>

</body>

</html>

The Math Object

The built-in Math Object includes mathematical constants and functions. You do not need to
create the Math object before using it.

To store a random number between 0 and 1 in a variable called “r_number”:


r_number=Math.random()

The Math object’s properties and methods are described below:

Properties Explanation
Math.E Euler’s constant (approximately 2.718281828459).
Math.LN2 The natural logarithm of 2 (approximately 0.6931471805599).
Math.LN10 The natural logarithm of 10 (approximately 2.302585092994).
Math.LOG2E The base 2 logarithm of Euler’s constant, e (approximately
1.442695040889).
Math.LOG10E The base 10 logarithm of Euler’s constant, e (approximately
0.4342944819033).
Math.PI The ratio of a circle’s circumference to its diameter (approximately
3.14159265359).
Math.SQRT1_2 The square root of one half (approximately 0.7071067811865).
Math.SQRT2 The square root of 2 (approximately 1.414213562373).
Math.abs(number) Returns the absolute value of number.
Math.cos(number) Returns the cosine of number.
Math.sin(number) Returns the sine of number.
Math.tan(number) Returns the tangent of number.
Math.acos(number) Returns the arc cosine, in radians of number. Returns 0 if number is out of
range.
Math.asin(number) Returns the arc sine, in radians, of number. Returns 0 if number is out of
range.
Math.atan(number) Returns the arc tangent, in radians, of number.
Math.ceil(number) Returns the greatest integer that is equal to or greater than number.
Math.floor(number) Returns the least integer that is equal to or less than number.
Math.exp(number) Returns the value of enumber. E is Euler’s constant-the base of the natural
algorithms.
Math.log(number) Returns the natural algorithm (base e) of number. If number is 0 or less
than 0, log returns -1.797693134862316e+308.
Math.max(number1, Returns the greater of number1 and number2.
number2)
Math.min(number1, Returns the lesser of number1 and number2.
number2)
Math.pow(base, Returns base exponent.
exponent)
Math.random() Returns a pseudo-random number between 0 and 1. Currently available on
UNIX platforms only.
Math.round(number) Returns the next higher integer value if the fractional part of number s .5
or greater. Returns the next lower integer value if the fractional part of
number is less than .5.
Math.sqrt(number) Returns the square root of number. sqrt() always returns 0 if number is out
of range.

Program

<html>

<head>

<title>Math Object</title>

</head>

<body>

<script language="JavaScript">
document.write("Math.E="+Math.E+"<br>");

document.write("Math.LN2="+Math.LN2+"<br>");

document.write("Math.LN10="+Math.LN10+"<br>");

document.write("Math.LOG2E="+Math.LOG2E+"<br>");

document.write("Math.LOG10E="+Math.LOG10E+"<br>");

document.write("Math.PI="+Math.PI+"<br>");

document.write("Math.SQRT1_2="+Math.SQRT1_2+"<br>");

document.write("Math.SQRT2="+Math.SQRT2+"<br>");

document.write("Math.abs(-125)="+Math.abs(-125)+"<br>");

document.write("Math.cos(60)="+Math.cos(60)+"<br>");

document.write("Math.sin(30)="+Math.sin(30)+"<br>");

document.write("Math.tan(45)="+Math.tan(45)+"<br>");

document.write("Math.acos(0.5)="+Math.acos(0.5)+"<br>");

document.write("Math.asin(0.5)="+Math.asin(0.5)+"<br>");

document.write("Math.atan(0.5)="+Math.atan(0.5)+"<br>");

document.write("Math.ceil(23.56928)="+Math.ceil(23.56928)+"<br>");

document.write("Math.floor(23.56928)="+Math.floor(23.56928)+"<br>");

document.write("Math.exp(0)="+Math.exp(0)+"<br>");

document.write("Math.log(2)="+Math.log(2)+"<br>");

document.write("Math.max(156,223)="+Math.max(156,223)+"<br>");

document.write("Math.min(156,223)="+Math.min(156,223)+"<br>");

document.write("Math.pow(2,5)="+Math.pow(2,5)+"<br>");

document.write("Math.random()="+Math.random()+"<br>");

document.write("Math.round(23.56928)="+Math.round(23.56928)+"<br>");

document.write("Math.sqrt(25)="+Math.sqrt(25)+"<br>");
</script>

</body>

</html>

Program: Random Numbers for 5000 Numbers

<html>

<head>

<title>Random Number</title>

</head>

<body>

<h4>Random Numbers</h4>

<script language="JavaScript">

total=0;

for(i=0;i<5000;i++)

num=Math.random();

total+=num;

window.status="Generated "+i+" numbers.";

average=total/5000;

average=Math.round(average*1000)/1000;

document.write("<h3> Average of 5000 numbers: "+average+"</h3>");

</script>

</body>

</html>

The Navigator Object


The navigator Object is a special object that stores information about the version of the
browser. This is a Netscape-specific tag, and it may or may not be implemented in other browsers

It is similar to the objects, such as window and document.

The navigator object includes several properties that reflect information about the version of
Netscape in use. These are all read-only properties:

 navigator.appcodeName is the browser’s code name, usually “Mozilla”.


 navigator.appName is the browser’s name, usually “Netscape”.
 navigator.appVersion is the version of Netscape being used- for example,
“2.0(Win98;I)”.
 navigator.userAgent is the user-agent header, which is sent to the host when requesting
a web page. It includes the entire version information, “Mozilla/2.0(Win95;I)”.

Program

<html>

<head>

<title>Navigator Object</title>

</head>

<body>

<script language="JavaScript">

document.write("Application Code Name="+navigator.appcodeName+"<br>");

document.write("Application Name="+navigator.appName+"<br>");

document.write("Application Version="+navigator.appVersion+"<br>");

document.write("Application User Agent="+navigator.userAgent+"<br>");

</script>

</body>

</html>

The <SCRIPT> Tag

Client-side JavaScript scripts are part of an HTML file, and are usually coded within the <SCRIPT>
and </SCRIPT> tags. Between these tags you may place any number of JavaScript statements, which will
be executed in the order they appear as part of the document loading process, <SCRIPT> tags may
appear in either the <HEAD> or <BODY> of an HTML document.

A single HTML document may contain more than one pair of (non-overlapping <SCRIPT> and
</SCRIPT> tags). These multiple separate scripts will have their statements executed in the order they
appear within the document. For example, you have the following script somewhere in an HTML page:

<SCRIPT type=”text/javascript”>
//JavaScript code goes here
</SCRIPT>

Or

<SCRIPT LANGUAGE=”JavaScript”>
//JavaScript code goes here
</SCRIPT>

</SCRIPT> tag to terminate the script.

JavaScript Files

A JavaScript file is just that pure JavaScript, without <SCRIPT> tags or any other HTML. A
JavaScript file typically has a .js extension.

The <SCRIPT> tag supports a new SRC attribute. The value of this attribute specifies the URL of a
file of JavaScript code. It is used like this:

<SCRIPT SRC=”../../javascript/util.js”></SCRIPT>

There are a number of advantages to using the SRC tag:

 It simplifies your HTML files by allowing you to remove large blocks of JavaScript code from
them.
 When you have functions or other JavaScript code used by several different HTML files, you can
keep it in a single file and read it into each HTML file that needs it. This reduces disk usage, and
makes code maintenance much easier.
 When JavaScript functions are used by more than one page, placing them in a separate
JavaScript file allows them to be cached by the browser, making them load much more quickly.

<NOSCRIPT> tag

The <noscript> tag allows you to specify HTML that is to be displayed if JavaScript is turned off or not
supported by the browser.

Syntax:
<NOSCRIPT>
//message for turned-off or not supported browser
</NOSCRIPT>

Program

<html>

<head>

<title>No Script Tag</title>

</head>

<body>

<script type="text/javascript">

document.write("<b> This browser supports JavaScript</b>");

</script>

<noscript>

document.write("<b> This browser not supports JavaScript</b>");

</noscript>

</body>

</html>

Manipulating Object Model

The DOM (Document Object Model) defines and describes these objects, their properties and
methods.

The browser provides us with a series of object. The HTML page displayed by the browser is
known as document object.

The Document object is most commonly used in client side JavaScript.

Event Handlers

Events are often used to trigger portions of a program. In JavaScript, events pertain to the web
page containing the script. When the user clicks on a link, selects or enters text, or even moves the
mouse over part of the page, an event occurs.
The script that you use to detect and respond to an event is called an event handler.

For example, the following piece of HTML code creates a button with the words “Click me!”;
clicking the button runs an piece of JavaScript code that adds together two numbers and displays the
result in a dialog box.

<FORM>
<INPUT TYPE=”submit” VALUE=”Click me!” onClick=”var sum=1+2; alert(sum);”>
</FORM>

Types of Events

There are different types of events such as mouse event, keyboard event and onload event. Etc.,
in JavaScript. The Table below shows list the types of events and their uses.

Event Name Description


onAbort Occurs when the user aborts the loading of an image
onBlur Occurs when an object on the page loses focus
onChange Occurs when a text field is changed by the user
onClick Occurs when the user clicks on an item
onError Occurs when a document or image can’t load correctly
onFocus Occurs when an item gains focus
onLoad Occurs when the page (or an image) finishes loading
onMouseOver Occurs when the mouse pointer moves over an item
onMouseOut Occurs when the mouse pointer moves off an item
onSelect Occurs when the user selects text in a text area
onSubmit Occurs when a submit button is pressed
onUnload Occurs when the user leaves the document or exits.

Program

<html>

<head>

<title>JavaScript Events</title>

<script language="JavaScript">

function greeting()

document.write("Welcome to the JavaScript Events");

}
function terminate()

conreturn=confirm("Are you Terminate!");

if(conreturn)

window.close();

</script>

</head>

<body onload="greeting()" onunload="terminate()">

</body>

</html>

Program: Form Events

<html>

<head>

<title>JavaScript Events</title>

<script language="JavaScript">

function TextChange(text)

alert(text);

function describe(text)

window.status=text;

return true;

}
function clearStatus()

window.status=''

function Selected(text)

window.status='Selected Text:'+text;

</script>

</head>

<body>

<h1>Description of Event Handler</h1>

<form>

Username:<input type="text" name="user" onChange="TextChange(this.value)"


onfocus="window.status='Please Enter the User Name' " onblur="alert('User Focus Lost')"><br>

Address:<textarea name="address" rows=5 cols=30 onfocus="window.status='Please


Enter the Address' " onblur="alert('Address Focus Lost')"
onselect="Selected(this.value)"></textarea><br>

<input type="button" value="Click me" onClick="alert('Clicked')">

<p>

<ul>

<li><a href="gmail.com" onmouseover="describe('Gmail Website');return true;"


onmouseout="clearStatus()">Gmail</a>

<li><a href="yahoo.com" onmouseover="describe('Yahoo Website');return


true;" onmouseout="clearStatus()">Yahoo</a>

</ul>

</p>
</form>

</body>

</html>

Validating and Submitting a Form

One of the most powerful features of the web is the use of interactive forms. JavaScript allows
the user to enter information and interact with the site, by single most useful validating forms. This
means using a script to verify that the information you enter is valid by form-based objects, submit and
reset.

The submit Object. The submit button was originally intended in HTML to be the final button a
user would click to send a form back to the server. With JavaScript, you can now use this button to also
send all of the information collected in a form to another window on your browser, or to the same
window itself.

Syntax:
<INPUT TYPE=”submit” NAME=”submitName” VALUE=”buttonText” [onClick=”handlerText”]>

You access these object’s properties and methods by the following syntax:

 submitName.propertyName
 submitName.methodName(parameters)
 formName.elements[index].propertyName
 formName.elements[index].methodName(parameters)

When you click a submit button, it always loads a new page-even if that page is the same page you were
already on. The submit object uses the onClick event handler and can be clicked by using the
submitName.click method.

The reset Object. The reset button allows a user to completely reset a form’s input fields to
their defaults.

Syntax:

<INPUT TYPE=”reset” NAME=”resetName” VALUE=”buttonText” [onClick=”handlerText”]>

You access these object’s properties and methods by the following syntax:

 resetName.propertyName
 resetName.methodName(parameters)
 formName.elements[index].propertyName
 formName.elements[index].methodName(parameters)
The reset button uses the same onClick event handler and click method as the submit object.

Example: Form Input Validation

<html>

<head>

<title>Form Validation</title>

<script language="JavaScript">

function validate()

if(document.form1.yourname.value.length<1)

alert('Please enter your full name.');

return false;

if(document.form1.address.value.length<1)

alert('Please enter your full address.');

return false;

if(document.form1.phone.value.length<1)

alert('Please enter your phone number.');

return false;

return true;

}
</script>

</head>

<body>

<h2>Form Validation Example</h2>

Enter the following information <br>

<form name="form1" action="post" onSubmit="validate()">

<p><b>Name:</b><input type="text" length="20" name="yourname"></p>

<p><b>Address:</b><textarea name="address" rows=5 cols=30


name="address"></textarea></p>

<p><b>Phone:</b><input type="text" length="20" name="phone"></p>

<p><input type="submit" value="Submit"></p>

</form>

</body>

</html>

Document Properties

The Document object has a number of properties that correspond to attributes of the <BODY>
tag, and which are used to specify the colors that the document is displayed in.

The Properties and Method of the document object is shown below:

Properties Explanation
title Specify the title of the web page
bgColor Specify the Background color of the document. The color value is either String or the
Hexadecimal digits (RRGGBB)
fgColor Specify the Foreground color of the text in document. The color value is either String or
the Hexadecimal digits (RRGGBB)
linkColor Specifies the color of the unvisited links
vlinkColor Specifies the color of the visited links
alinkColor Specifies the color of the activated links
lastModified Specify the date and time of the most recent change of the document.

Method Explanation
Write Display some text in the web page
Program

<html>

<head>

<title>Document Object</title>

</head>

<body>

<script type="text/javascript">

document.title="Example for Document Object Properties"

document.bgColor="orange"

document.fgColor="yellow"

document.linkColor="blue"

document.alinkColor="magenta"

document.vlinkColor="green"

document.write("Date of Last Modified:"+document.lastModified)

</script>

<p><a href="D:\ANIMATION\Baby\3.jpg">Click Here</a></p>

</body>

</html>

Object Hierarchy

This hierarchy includes a variety of browser objects that represent data on the current web page
and in the current browser window.

The browser objects are arranged into a hierarchy of parent and child objects. When you refer
to an object, you use the parent object name followed by the child object names or names, separated by
periods. For example, JavaScript stores objects to represent images in a document as children of the
document object. The following refers to the image6 object, a child of the document object, which is a
child of the window object:

Window.document.image6
A diagram of the object hierarchy is given in Figure Below which serves as the parent object for most of
the other objects.

document links()

anchors()
Window
history
(parent, frames[],self,top)
images()

location
forms() form elements

Figure : JavaScript Browser Object Hierarchy

Windows and Frames:

The Window Object

The window object is at the top of the object hierarchy. A window object exists for each open
browser window. The properties of this object describe the document in the window and provide
information about the window. Three of the window object’s properties are child objects:

 The location object stores the location (URL) that is displayed in the window.
 The document object holds the web page itself.
 The history object contains a list of sites visited before and after the current site.

Window Object Properties

Property Explanation
Name Return the name of the current window
Parent Return the parent window of the current window
Self Return the current window
Top Returns the topmost browser window
Status Change the status of the current window

Program

<html>

<head>
<title>Window Properties</title>

<script language="JavaScript">

function pageShow()

MyWin=window.open('MyWindow','_top','status=yes');

//MyWin=window.open('','MyWindow');

MyWin.title='My New Window';

MyWin.status='Hai This is Window Object';

MyWin.document.write('Title='+MyWin.title+'<br>');

MyWin.document.write('Name='+MyWin.name+'<br>');

//window.location.href="WindowObject.html";

</script>

</head>

<body>

<form>

<input type="button" value="Click Me" onClick="pageShow()">

</form>

</body>

</html>

Creating a new window

You can create a new browser window with the window.open() method enables you to open a
new browser window. A typical statement to open a new window looks like this:
WindowName=window.open(“URL”,”WindowName”,”Feature List”);

The following are the components of the window.open() statement:


 The WindowName variable is used to store the new window object. You can access the methods
and properties of the new object by using this name.
 The First parameter of the window.open() method is an URL, which will be loaded into the new
window left blank, no web page will be loaded.
 The Second Parameter specifies a window name(here, WindowName again). This is assigned to
the window object’s name property and is used for target window.
 The third parameter is a list of optional features, separated by commas. You can customize the
new window by choosing whether to include the toolbar, status line, and other features. This
enables you to create a variety of “floating” windows, which may look nothing like a typical
browser window.

The features available in the third parameter of the window.open() method include width and height, to
set the size of the window, and several features that can be set to either yes(1) or no(0): toolbar,
location, directories, status, menubar, scrollbars, and resizable. You can list only the features you want
to change from the default. This example creates a small window with no toolbar or status line:
SmallWin=window.open(“”,”small”,width=100,height=120,toolbar=0,status=0);
Opening and Closing Windows

Of course, you can close windows as well. The window.close() method closes a window. Its main
purpose is for closing windows you have created. For example, this statement closes a window called
updatewindow:
updatewindow.close();

Program

<html>

<head>

<title>Create a New Window</title>

</head>

<body>

<h1>Create a New Window</h1>

<hr>

Use the buttons below to test opening and closing windows in JavaScript.

<hr>

<form name="winform">
<input type="button" value="Open a New Window"
onClick="NewWin=window.open('','self','toolbar=no,status=no,width=200,height=200');">

<p><input type="button" value="Close New Window" onClick="NewWin.close();">

<p><input type="button" value="Close Main Window" onClick="window.close();">

</form>

</body>

</html>

Displaying Dialogs

The window object includes three methods which are useful for displaying messages and
interacting with the user:

Method Explanation
alert() Displays an alert dialog box
confirm() Displays a confirmation dialog with OK and Cancel Button. If OK is Pressed return
true and false if Cancel is pressed.
prompt() Displays a message and prompts the user for input. It returns the text entered by
the user.

Program

<html>

<head>

<title>Alerts, Confirmation, and Prompts</title>

</head>

<body>

<h1>Alerts, Confirmation, and Prompts</h1>

<hr>

Use the buttons below to test dialogs in JavaScript.

<hr>

<form name="winform">

<p><input type="button" value="Alert" onClick="window.alert('This is a test alert.');">


<p><input type="button" value="Confirmation" onClick="var temp=window.confirm('Would you
like to Confirm?'); window.status=(temp)?'confirm:true':'confirm:false';">

<p><input type="button" value="Prompt" onClick="var temp=window.prompt('Enter some


text:','Enter the value'); window.status=temp;">

</form>

</body>

</html>

Using Frames

Some browsers (including the latest Netscape and Microsoft browsers) support frames or
framesets. These enable you to divide the browser window into multiple panes, called frames. Each
frame can contain a separate URL or the output of a script.

Using JavaScript Object for Frames

When a window contains multiple frames, each frames is represented in JavaScript by a frame
object. This object is equivalent to a window object, but it is used for dealing with that frame. The frame
object’s name is the same the NAME attribute you give it in the <FRAME> tag.

The window and self keyword refer to the current window. Another keyword parent enables you
to refer to the main window. Each frame object in a window is a child of the parent window object.

Program

<html>

<head>

<title>Frame Tag</title>

<frameset rows="*,*" cols="*,*" bordercolor="blue">

<frame name="topleft" src="WindowDialogs.html" >

<frame name="topright" src="WindowObject.html" >

<frame name="bottomleft" src="WindowProperties.html">

<frame name="bottomright" src="First.html">

</frameset>

</noframe>
</head>

</html>

The frames Array

This frame array stores information about each of the frames in the document. The frames are
indexed starting with zero and beginning with the first <FRAME> tag in the frameset document.

As an example, you could refer to the frames defined in above using array references:

 parent.frames[0] is equivalent to the topleft frame.


 parent.frames[1] is equivalent to the topright frame.
 parent.frames[2] is equivalent to the bottomleft frame.
 parent.frames[3] is equivalent to the bottomright frame.

Frame Object Properties, Events, and Methods

Each frame object (or each member of the frames array) has two properties:

 name is the value of the NAME attribute in the <FRAME> tag.


 length is the number of child frames within the frame.

Creating a Navigation Framed Document

Program

<html>

<head>

<title>Frame Document</title>

</head>

<frameset cols="*,*">

<frame name="left" src="FrameNavigation.html">

<frame name="right" src="about:blank">

</frameset>

</html>

Program: FrameNavigation.html

<html>
<head>

<title>Navigation Frame</title>

</head>

<body>

<p>To load a page into the right - hand frame</p>

<ul>

<li><a href="#" onClick="parent.right.location='MathObject.html';


window.location='MathObject.html';">Math Object</a>

<li><a href="#" onClick="parent.right.location='StringObject.html';


window.location='StringObject.html';">String Object</a>

</ul>

</body>

</html>

JavaScript URLs

Another way that JavaScript code can be included on the client side is in a URL following the

javascript:pseudo-protocol specifier.

The special protocol type specifies that the body of the URL is arbitrary JavaScript code to be
interpreted by the JavaScript interpreter. If the JavaScript code in a JavaScript URL contains multiple
statements, the statements must be separated from one another by semicolons. Such as URL might look
like the following:

javascript:var now=new Date(); “<h1>The time is:</h1>”+now;

When the browser “loads” one of these JavaScript URLs, it executes the JavaScript code
contained in the URL and displays the “document” referred to by the URL. This “document” is the string
value of the last JavaScript statement in the URL. This string will be formatted and displayed just like any
other document loaded into the browser.

More commonly, a JavaScript URL will contain JavaScript statements that perform actions but
return no value. For example:
javascript:alert(“Hello World!”)
When this sort of URL is “loaded,” the browser executes the JavaScript code, but, because there
is no value to display as the new document, it does not modify the currently displayed document.

Program

<html>

<head>

<title>Javascript URLs</title>

</head>

<body>

<script language="JavaScript">

javascript:alert("Hello World!")

javascript:var now=new Date();

javascript:document.write("<h1> The time is:</h1>"+now);

</script>

</body>

</html>

JavaScript and Client-side Image Maps

A common use for graphics on the Web is in image maps-large images with clickable areas. Each
area can link to a separate page. There are two types of image maps:

 Server-side image maps require a CGI script to interpret the user’s actions.
 Client-side image maps are embedded in HTML, and require no interaction with the
server. This is a newer standard and not officially part of HTML, but it is supported by
most browsers.

The client-side image maps and JavaScript work well together. You can use client-side image
maps with JavaScript in three ways:

 As with any link, you can link areas of the map to javascript: method URLs to execute
functions.
 Each <AREA> tag, which defines a clickable area, can have event handlers:
onMouseOver, onMouseOut, and onClick. These function in the same way as the
corresponding link and image event handlers.
 Each <AREA> tag is reflected in an area object. These objects are part of the links array,
and have the same properties.

Using an image Map with JavaScript

As an example of using a client-side image map with JavaScript, let’s create a simple image map
menu for a fictional company.

To create a client-side map, you need to do two things:

 Use your favorite graphics application to create the actual graphic as a GIF or JPEG image.
 Create a MAP definition that describes areas in the image.
 Include the image in the document, using the USEMAP attribute to point to the MAP definition.

Program

<html>

<head>

<title>Image Map Example</title>

<script language="JavaScript">

function update(text)

document.form1.text1.value=text;

</script>

</head>

<body>

<map name="map1">

<area shape=RECT COORDS="14,15,151,87" HREF="javascript:update('service');"


onMouseOver="window.status='Service Department'; return true;">

<area shape=RECT COORDS="162,16,283,85" HREF="javascript:update('sales');"


onMouseOver="window.status='Sales Department'; return true;">

<area shape=RECT COORDS="294,15,388,87" HREF="javascript:update('spares');"


onMouseOver="window.status='Spares Department'; return true;">
<area shape=RECT COORDS="13,98,79,178" HREF="javascript:update('email');"
onMouseOver="window.status='Email Us'; return true;">

<area shape=RECT COORDS="92,97,223,177" HREF="javascript:update('stock');"


onMouseOver="window.status='Stock Maintenance'; return true;">

<area shape=RECT COORDS="235,98,388,177" HREF="javascript:update('staff members');"


onMouseOver="window.status='Our Staff Members'; return true;">

<area shape=default HREF="javascript:update('No item selected');"


onMouseOver="window.status='Please select an item'; return true;">

</map>

<h1>Client-Side Image Map Example</h1>

<hr>

Click on the image on the respective area of department and see the text box and status bar.

<hr>

<img src="IMG.JPG" USEMAP="#map1">

<hr>

<form name="form1">

<b>Clicked Item:</b>

<input type="text" name="text1" value="Please Select an Item.">

</form>

<hr>

</body>

</html>

Cookies

A cookie is a chunk of information sent by the server, which can be stored on the client. Cookies
are stored with a date they expire and the name of the host from which they came. When user
communicates with the same host later, the data is sent back.

Here are some examples where cookies can be useful:


 They can store a user’s “preferences” for a Web page. When users return to the page, they can
view it in their desired fashion. For example, Netscape’s home page uses this technique to turn
frames on or off based on user’s preference.
 They can maintain state between CGI scripts or JavaScript programs. For example, a quiz might
ask you one question, then load a new page for the next question, storing your score in a cookie.
 They can remember information so that users can avoid entering it every time they access a
page. For example, a page that requires a user’s name can remember it with a cookie.

Cookies can also be used in JavaScript. You can use them to store information between pages, or
event to store information on users’ computers to remember their preferences next time they load your
page.

The cookies are stored in a “cookie jar” on the user’s computer. Specifically, each cookie is a line
in a file called cookies.txt, usually in the same directory as Netscape itselt.

Cookies are stored for the current document; and they are accessed with the document.cookie
property. This property is a text value which can contain the following components:

 name=value: A name and value, separated by the equal sign. This is the actual data
stored in the cookie.
 expires=date: An expiration date. If this date is not included, the cookie is erased when
the user exits the browser. (For the format of the date)
 domain=machine: The domain name for which the cookie is valid. By default, this is the
domain of the current page.
 path=path: The URL path for which the cookie is valid. By default, this is the current URL.

Program

<html>

<head>

<title>The Page that remembers your name</title>

<script>

if(document.cookie.substring(0,2)!="n=")

nam=window.prompt("Enter your name");

document.cookie=" "+nam+";";

document.cookie+="expires=Monday, 04-Feb-2019 11:58:57 GMT"

}
</script>

</head>

<body>

<h1>Here is Your Cookies</h1>

<hr>

<script>

indx=document.cookie.indexOf(";");

nam=document.cookie.substring(0,indx+1);

document.write("<b>Hello there ",nam);

</script>

</body>

</html>

JAVA CONSOLE

Integrating Java with HTML

Unlike JavaScript, Java code is never included in the HTML file itself. Instead, a special HTML tag,
<APPLET>, is used to embed the applet in the Web page. Here is a simple example of an applet:
<applet code=”Applet1.class” width=55 height=68></applet>

Notice that both opening and closing <APPLET> tags are required. Between them, you can use
optional <PARAM> tags to give parameters to the applet. The parameters required depend on the
applet. Each <PARAM> tag includes a variable name and value:

<PARAM name=height value=100>

Creating a Simple Java Applet

Now create a simple Java applet show in below:

Program (JavaTest.java) A simple Java applet that displays a message.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Font;
public class JavaTest extends Applet

Font f=new Font("TimesRoman",Font.BOLD,60);

public void paint(Graphics g)

g.setFont();

g.drawString("Text from Java",15,50);

Example(Java1.html)

<html>

<head>

<title>Simple Java Test</title>

</head>

<body>

<h1>test</h1>

<hr>

An applet is included below to display some text.

<hr>

<applet code="JavaTest.class" width=450 height=125>

</applet>

</body>

</html>

Using Java Classes with JavaScript

In Netscape Navigator 3.0 and above introduced a new feature called LiveConnect. Which
provides the following capabilities:
 JavaScript programs can communicate with and control Java applets.
 Java applets can access JavaScript objects, properties and methods.
 JavaScript programs can control Netscape plug-ins.

Calling Java Methods


You can call java methods directly from JavaScript. This means you can treat methods as if they
are JavaScript statements themselves. For example, this statement prints a message to the Java console:
java.lang.System.out.println(“This is a test.”);
This will be most useful if you are an experienced Java programmer. If you are not, you can use
JavaScript to take advantage of features of existing Java applets.

The applet Object

Each Java applet you embed in a Web page is made available to JavaScript as an applet object,
with the same name as the applet’s class name. The applet object resides in the object hierarchy under
the document object. For example, a Java applet called Scroll would be accessed through an object
called document.Scroll.

The objects, properties, and methods of the applet are then available to JavaScript, provided the
Java programmer has made them public.

Controlling a Java Applet

Let’s create a Java applet that can be manipulated from within JavaScript. The below java
example shows the Java source code.

Example (ControlJava.java) A Java Applet that can be controlled via JavaScript.

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Font;

public class ControlJava extends Applet

Font f=new Font("TimesRoman",Font.BOLD,60);

String message;

public void init()

message=new String("Java Test");


}

public void setMessage(String msgText)

message=msgText;

repaint();

public void paint(Graphics g)

g.setFont(f);

g.drawString(message,15,50);

This applet now includes a setMessage() method to change the text in the display. The below
HTML example shows the HTML and JavaScript document used to control the applet.

Example:(CJava.html) The JavaScript program to control the Java applet.

<html>

<head>

<title>Control a Java Applet</title>

</head>

<body>

<h1>Control a Java Applet</h1>

<hr>

The Java applet below displays text in a large font. You can enter new text to display in the form
below, and JavaScript will call the Java applet to change the text.

<hr>

<form name="form1">
<input type="text" name="text1">

<input type="button" value="Change Text"


onClick="document.ControlJava.setMessage(doucment.form1.text1.value);">

</form>

<hr>

<applet name="ControlJava" code="ControlJava.class" width=450 height=125>

</applet>

<hr>

End of Page

</body>

</html>

This uses a simple event handler to call the Java applet’s setMessage() method. The string you
enter in the text field is passed to the applet and displayed in place of the original string.

Calling JavaScript Functions from Java


It’s also possible to call JavaScript functions, and access JavaScript objects and properties, from
within Java. This enables you to use JavaScript’s unique capabilities, such as reading the values of form
elements, in powerful Java applications.
To make JavaScript functions accessible from Java, you need to configure things both in
JavaScript and in Java. You’ll look at the required steps.

Steps for the JavaScript Programmer

It’s possible for a Java applet to do things you don’t want it to, so you must give permission for it
to access your JavaScript program and objects. To do this, add the MAYSCRIPT attribute to the
<APPLET> tag that embeds the applet:
<APPLET CODE=”Script.class” NAME=”TestApp” MAYSCRIPT>

</APPLET>
Steps for the Java Programmer
For the Java Programmer, there are also some important steps before you can access JavaScript.
First, you need to include the netscape.javascript package, which provides these functions, in your
imported classes:

import netscape.javascript.*
Next, you need to create a handle for the JavaScript window. To do this, define a variable of
type JSObject and use the getWindow method to assign it:

JSObject js=new JSObject;


js=JSObject.getWindow(this);

Accessing JavaScript Objects

Once you have a handle for the JavaScript window, you can get the objects you need to access.
To do this, you need to call the getMember method for each property. For example, to make the text1
field on the form1 form accessible:
js=JSObject.getWindow(this);
JSObject document=(JSObject)js.getMember(“document”);
JSObject form1=(JSObject)document.getMember(“form1”);
JSObject text1=(JSObject)form1.getMember(“text1”);
You are creating an object of type JSObject for the document, then for each object underneath it.

Calling JavaScript Functions

You can also call JavaScript functions and methods from within Java, using the same technique.
The two methods you use for this purpose are call and eval. For example, this statement calls a
JavaScript method to display an alert message:

js=JSObject.getWindow(this);

js.call(“window.alert(‘This is a test.’);”);

--END--

You might also like