Nothing Special   »   [go: up one dir, main page]

WIDT UNIT-III

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

UNIT – III

Client side Validation: Introduction to JavaScript - What is DHTML, JavaScript,


basics, variables, string manipulations, mathematical functions, statements,
operators, arrays, functions. Objects in JavaScript - Data and objects in
JavaScript, regular expressions, exception handling. DHTML with JavaScript -
Data validation, opening a new window, messages and confirmations, the status bar,
different frames, rollover buttons, moving images.

1) What is JavaScript ?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0Brendan Eich in 1995, in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet Explorer,
and other web browsers.
Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus,
it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.

<script>... </script>:
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script>.
You can place the <script> tags, containing your JavaScript, anywhere within your web
page, but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>

The script tag takes two important attributes −

 Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".

So your JavaScript segment will look like −

<script language="javascript" type="text/javascript">


JavaScript code
</script>
we can place JavaScript in an HTML file in different ways.
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere,
then you will place that script in the head as follows −
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" value="Say Hello" />
</body>
</html>

JavaScript in <body>...</body> section If you need a script to run as the page loads so that the
script generates content in the page, then the script goes in the <body> portion of the document. In
this case, you would not have any function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as follows
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" value="Say Hello" />
</body>
</html>
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of a
site.
You are not restricted to be maintaining identical code in multiple HTML files. The script
tag provides a mechanism to allow you to store JavaScript in an external file and then
include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML
code using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>

<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}

2)Javascript Data Types:


JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.

Primitive data type

Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

var a=40;//holding number

var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100


Boolean represents Boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

3) JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer
to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible within


the function or block only. For example:

<script>
function abc(){
var x=10;//local variable
}
</script>
JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as global variable. For
example:

<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

4)JavaScript Operators

JavaScript operators are symbols that are used to perform operations on operands. For
example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus 20%10 = 0
(Remainder)

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false


<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true


JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.


5)Math object:
The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and
methods of Math are static and can be called by using Math as an object without creating
it.

Thus, you refer to the constant pi as Math.PI and you call the sine function as
Math.sin(x), where x is the method's argument.

Syntax

The syntax to call the properties and methods of Math are as follows

var pi_val = Math.PI;


var sine_val = Math.sin(30);

Math Methods

Here is a list of the methods associated with Math object and their description

Sr.No Method & Description

abs()
1
Returns the absolute value of a number.
acos()
2
Returns the arccosine (in radians) of a number.
asin()
3
Returns the arcsine (in radians) of a number.
atan()
4
Returns the arctangent (in radians) of a number.
atan2()
5
Returns the arctangent of the quotient of its arguments.
ceil()
6
Returns the smallest integer greater than or equal to a number.
cos()
7
Returns the cosine of a number.
exp()
8
Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.
floor()
9
Returns the largest integer less than or equal to a number.
log()
10
Returns the natural logarithm (base E) of a number.
max()
11
Returns the largest of zero or more numbers.
min()
12
Returns the smallest of zero or more numbers.
pow()
13
Returns base to the exponent power, that is, base exponent.
random()
14
Returns a pseudo-random number between 0 and 1.
round()
15
Returns the value of a number rounded to the nearest integer.
sin()
16
Returns the sine of a number.
sqrt()
17
Returns the square root of a number.
tan()
18
Returns the tangent of a number.

<html>
<head>
<title>
JavaScript Math Object
</title>
</head>
<body>
<h2>JavaScript Math Object</h2>

<p id="GFG" style = "color:green;"></p>


<script>
document.getElementById("GFG").innerHTML =
"<p><b>Math.abs(-4.7):</b> " + Math.abs(-4.7) + "</p>" +
"<p><b>Math.ceil(4.4):</b> " + Math.ceil(4.4) + "</p>" +
"<p><b>Math.floor(4.7):</b> " + Math.floor(4.7) + "</p>" +
"<p><b>Math.sin(90 * Math.PI / 180):</b> " +
Math.sin(90 * Math.PI / 180) + "</p>" +
"<p><b>Math.min(0, 150, 30, 20, -8, -200):</b> " +
Math.min(0, 150, 30, 20, -8, -200) + "</p>" +
"<p><b>Math.random():</b> " + Math.random() + "</p>";
</script>
</body>

</html>
6)JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal

The string literal is created using double quotes. The syntax of creating string using
string literal is given below:

var stringname="string value";

<script>
var str="This is string literal";
document.write(str);
</script>
2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.


<script>

var stringname=new String("hello javascript string");


document.write(stringname);
</script>
String Methods

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified


index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.

search() It searches a specified regular expression in a given string and returns


its position if a match occurs.

match() It searches a specified regular expression in a given string and returns


that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.

substring() It is used to fetch the part of the given string on the basis of the
specified index.

slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.


toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s
current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly created
array.

trim() It trims the white space from the left and right side of the string.

<html>
<head>
<title>STRINGS METHODS</title>
</head>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);

</script>
</body>

</html>

7)Array:
An array is a special variable, which can hold more than one value at a time.

JavaScript arrays are used to store multiple values in a single variable.

An array can hold many values under a single name, and we can access the values by
referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array_name = [item1, item2, ...];

Example

var cars = ["HYUNDAI", "Volvo", "BMW"];

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example

var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array

You refer to an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];

This statement modifies the first element in cars:

cars[0] = "Opel";
Methods

pop():

Javascript array pop() method removes the last element from an array and returns that
element.

Syntax

Its syntax is as follows −

array.pop();

Return Value

Returns the removed element from the array.

<script type="text/javascript">

var numbers = [1, 4, 9];

var element = numbers.pop();

document.write("element is : " + element );

var element = numbers.pop();

document.write("<br />element is : " + element );

</script>

push():

Javascript array push() method appends the given element(s) in the last of the array
and returns the length of the new array.

Syntax

Its syntax is as follows −

array.push(element1, ..., elementN);

Parameter Details

element1, ..., elementN: The elements to add to the end of the array.

Return Value

Returns the length of the new array.

<script type="text/javascript">

var numbers = new Array(1, 4, 9);

var length = numbers.push(10);

document.write("new numbers is : " + numbers );


length = numbers.push(20);

document.write("<br />new numbers is : " + numbers );

</script>

shift():

Javascript array shift()method removes the first element from an array and returns that
element.

Syntax

Its syntax is as follows −

array.shift();

Return Value

Returns the removed single value of the array.

var element = [105, 1, 2, 3].shift();

document.write("Removed element is : " + element );

unshift():

Javascript array unshift() method adds one or more elements to the beginning of an
array and returns the new length of the array.

Syntax

Its syntax is as follows −

array.unshift( element1, ..., elementN );

Parameter Details

element1, ..., elementN − The elements to add to the front of the array.

Return Value

Returns the length of the new array. It returns undefined in IE browser.

var arr = new Array("orange", "mango", "banana", "sugar");

var length = arr.unshift("water");

document.write("Returned array is : " + arr );

document.write("<br /> Length of the array is : " + length );

splice():

Javascript array splice() method changes the content of an array, adding new elements
while removing old elements.
Syntax

Its syntax is as follows −

array.splice(index, howMany, [element1][, ..., elementN]);

Parameter Details

index − Index at which to start changing the array.

howMany − An integer indicating the number of old array elements to remove. If


howMany is 0, no elements are removed.

element1, ..., elementN − The elements to add to the array. If you don't specify any
elements, splice simply removes the elements from the array.

Return Value

Returns the extracted array based on the passed parameters.

<script type="text/javascript">

var arr = ["orange", "mango", "banana", "sugar", "tea"];

var removed = arr.splice(2, 0, "water");

document.write("After adding 1: " + arr );

document.write("<br />removed is: " + removed);

removed = arr.splice(3, 1);

document.write("<br />After adding 1: " + arr );

document.write("<br />removed is: " + removed);

</script>

concat():

Javascript array concat() method returns a new array comprised of this array joined
with two or more arrays.

Syntax

The syntax of concat() method is as follows −

array.concat(value1, value2, ..., valueN);

valueN − Arrays and/or values to concatenate to the resulting array.

Return Value

Returns the length of the array.

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

var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

document.write("alphaNumeric : " + alphaNumeric );

</script>

slice():

Javascript array slice() method extracts a section of an array and returns a new array.

Syntax

Its syntax is as follows −

array.slice( begin [,end] );

Parameter Details

begin − Zero-based index at which to begin extraction. end − Zero-based index at


which to end extraction.

Return Value

Returns the extracted array based on the passed parameters.

<script type="text/javascript">

var arr = ["orange", "mango", "banana", "sugar", "tea"];

document.write("arr.slice( 1, 2) : " + arr.slice( 1, 2) );

document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) );

</script>

sort():

Javascript array sort() method sorts the elements of an array.

Syntax

Its syntax is as follows −

array.sort( compareFunction );

Parameter Details

compareFunction − Specifies a function that defines the sort order. If omitted, the
array is sorted lexicographically.

Return Value

Returns a sorted array.


Example

Try the following example.

<html>

<head>

<title>JavaScript Array sort Method</title>

</head>

<body>

<script type="text/javascript">

var arr = new Array("orange", "mango", "banana", "sugar");

var sorted = arr.sort();

document.write("Returned string is : " + sorted );

</script>

</body>

</html>

8)Functions:
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps programmers
in writing modular codes. Functions allow a programmer to divide a big program into a
number of small and manageable functions.

JavaScript allows us to write our own functions as well.

Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique function
name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.

Syntax
The basic syntax is shown here.
<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters −
<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the
name of that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be captured
inside the function and any manipulation can be done over those parameters. A function
can take multiple parameters separated by comma.

Example

Try the following example. We have modified our sayHello function here. Now it takes
two parameters.

<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement

A JavaScript function can have an optional return statement. This is required if you want
to return a value from a function. This statement should be the last statement in a
function.

For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.
Example

Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.

<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

9)Regular Expressions:
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String
and RegExp define methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);


or simply
var pattern = /pattern/attributes;
Here is the description of the parameters −

 pattern − A string that specifies the pattern of the regular expression or another
regular expression.
 attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multi-line matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used
to find a range of characters.

[...]
Any one character between the brackets.

[^...]
Any one character not between the brackets.

[0-9]
It matches any decimal digit from 0 through 9.

[a-z]
It matches any character from lowercase a through lowercase z.

[A-Z]
It matches any character from uppercase A through uppercase Z.

[a-Z]
It matches any character from lowercase a through uppercase Z.

Quantifiers
The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.

p+
It matches any string containing one or more p's.
p*
It matches any string containing zero or more p's.

p?
It matches any string containing at most one p.

p{N}
It matches any string containing a sequence of N p's

p{2,3}
It matches any string containing a sequence of two or three p's.

p{2, }
It matches any string containing a sequence of at least two p's.

p$
It matches any string with p at the end of it.

^p It matches any string with p at the beginning of it.


Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts
to give the combination a special meaning.

\s
a whitespace character (space, tab, newline)

\S
non-whitespace character

\d
a digit (0-9)

\D
a non-digit

\w
a word character (a-z, A-Z, 0-9, _)

\W
a non-word character

[\b]
a literal backspace (special case).

[aeiou]
matches a single character in the given set

[^aeiou]
matches a single character outside the given set
(foo|bar|baz)
matches any of the alternatives specified
<head>
<title>Match a Single Character Using Regular Expression in JavaScript</title>
</head>
<body>
<script>
var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
if(regex.test(str)) {
document.write("Match found!");
} else {
document.write("Match not found.");
}
</script>
</body>
</html>
Ex2
<html>
<head>
<title>JavaScript Find and Replace Characters in a String Using Regular
Expression</title>
</head>
<body>
<script>
var regex = /\s/g;
var replacement = "-";
var str = "Earth revolves around\nthe\tSun";
document.write("<pre>" + str + "</pre>");
document.write("<pre>" + str.replace(regex, replacement) + "</pre>");
document.write("<pre>" + str.replace(/ /g, "-") + "</pre>");
</script>
</body>
</html>
10)JavaScript - Errors & Exceptions Handling:
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors,
and (c) Logical Errors.

Syntax Errors

Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.

For example, the following line causes a syntax error because it is missing a closing
parenthesis.

<script type="text/javascript">

window.print(;

</script>

When a syntax error occurs in JavaScript, only the code contained within the same thread
as the syntax error is affected and the rest of the code in other threads gets executed
assuming nothing in them depends on the code containing the error.

Runtime Errors

Runtime errors, also called exceptions, occur during execution (after


compilation/interpretation).

For example, the following line causes a runtime error because here the syntax is correct,
but at runtime, it is trying to call a method that does not exist.

<script type="text/javascript">

window.printme();

</script>

Exceptions also affect the thread in which they occur, allowing other JavaScript threads
to continue normal execution.

Logical Errors

Logic errors can be the most difficult type of errors to track down. These errors are not
the result of a syntax or runtime error. Instead, they occur when we make a mistake in
the logic that drives our script and we do not get the result as we expected.

The try...catch...finally Statement

The latest versions of JavaScript added exception handling capabilities. JavaScript


implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
we can catch programmer-generated and runtime exceptions, but we cannot catch
JavaScript syntax errors.

Here is the try...catch...finally block syntax −

<script type="text/javascript">

try {

Code to run

[break;]

catch ( e ) {

Code to run if an exception occurs

[break;]

finally {

Code that is always executed regardless of

an exception occurring

</script>

The try block must be followed by either exactly one catch block or one finally block
(or one of both). When an exception occurs in the try block, the exception is placed in
e and the catch block is executed. The optional finally block executes unconditionally
after try/catch.

You can use finally block which will always execute unconditionally after the try/catch.

The throw Statement

We can use throw statement to raise your built-in exceptions or your customized
exceptions. Later these exceptions can be captured and you can take an appropriate
action.

<html>

<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">

<button type="button" Input</button>


<p id="p01"></p>

<script>

function myFunction() {

var message, x;

message = document.getElementById("p01");

message.innerHTML = "";

x = document.getElementById("demo").value;

try {

if(x == "") throw "empty";

if(isNaN(x)) throw "not a number";

x = Number(x);

if(x < 5) throw "too low";

if(x > 10) throw "too high";

catch(err) {

message.innerHTML = "Input is " + err;

</script>

</body>

</html>

11)Creating Objects in JavaScript


There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
1. Var object={property1:value1,property2:value2...propertyN:valueN}
property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.

<script>

var emp={id:102,name:"Shyam Kumar",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

Output of the above example


102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Test it Now
Output of the above example
101 Ravi 50000

3) By using an Object constructor


Here, we need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;

e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

</script>

Output of the above example


103 Vimal Jaiswal 30000
JavaScript Object Properties

Properties are the values associated with a JavaScript object.

A JavaScript object is a collection of unordered properties.

Accessing JavaScript Properties

The syntax for accessing the property of an object is:

objectName.property // person.age

or

objectName["property"] // person["age"]

Adding New Properties

You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists - you can then give it new properties:

Example
person.nationality = "English";

JavaScript Object Methods


JavaScript methods are the actions that can be performed on objects.
Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example
name = person.fullName();

12)document object:

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is


the root element that represents the html document. It has properties and methods.
By the help of document object, we can add dynamic content to our web page.

Methods of document object

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the
end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" value="print name"/>
</form>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" > </form>

Window Object
The window object represents a window in browser. An object of window is created automatically by
the browser.

Methods of window object

alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating expressions
etc.

<html>

<body>

<p>Click the button to open a new window called "MsgWindow" with some text.</p>

<button >

<button </button>

<script>

function myFunction() {
myWindow= window.open("", "_blank",
"toolbar=yes,scrollbars=yes,resizable=no,top=200,left=300,width=400,height=400");

myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px


tall!</p>");

function closeWin() {

myWindow.close();

</script>

</body>

</html>

EX:<html>

<body>

<script type="text/javascript">
function msg(){
setTimeout(
function(){
alert("Welcome to Javatpoint after 2 seconds")
},2000);

}
</script>

<input type="button" value="click" >
</body>

</html>

Navigator Object:
The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.

appName returns the name

appVersion returns the version

appCodeName returns the code name


platform returns the platform e.g. Win32.

<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion); </script
>

Date Object:

The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.

Constructor

You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods

getDate() It returns the integer value between 1 and 31 that represents the day for
the specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the day of the
week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis of local
time.
getHours() It returns the integer value between 0 and 23 that represents the hours on
the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents the minutes
on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents the month on
the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents the seconds
on the basis of local time.

setDate() It sets the day value for the specified date on the basis of local time.

setMonth() It sets the month value for the specified date on the basis of local time.

Current Time: <span id="txt"></span>


<script>
window. > function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
}
</script>

13)Why Use DHTML?

DHTML makes a webpage dynamic but Javascript also does, the question arises that
what different does DHTML do? So the answer is that DHTML has the ability to change a
webpages look, content and style once the document has loaded on our demand without
changing or deleting everything already existing on the browser’s webpage. DHTML can
change the content of a webpage on demand without the browser having to erase
everything else, i.e. being able to alter changes on a webpage even after the document
has completely loaded.

Difference between HTML and DHTML:


 HTML is a markup language while DHTML is a collection of technologies.
 HTML is used to create static webpages while DHTML is capable of creating dynamic
webpages.
 DHTML is used to create animations and dynamic menus but HTML not used.
 HTML sites are slow upon client-side technologies whereas DHTML sites are
comparatively faster.
 Web pages created using HTML are rather simple and have no styling as it uses only
one language whereas DHTML uses HTML, CSS, and Javascript which results in a
much better and way more presentable webpage.
 HTML cannot be used as server side code but DHTML used as server side code.
 DHTML needs database connectivity but not in case of HTML.
 Files in HTML are stored using .htm or .html extension while DHTML uses .dhtm
extension.
 HTML requires no processing from the browser but DHTML does.

14)Form Validation:
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct information. This was really
a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending
it to the web server. Form validation generally performs two functions.
● Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
● Data Format Validation − Secondly, the data that is entered must be checked
for correct form and value. our code must include appropriate logic to test
correctness of data

EX-1
<html>
<body>
<script>
● function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>

<form name="myform" method="post" validateform()" >


Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Ex 2:
email validation

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" validateema
il();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>

15)Window object:
Open() :
The open() method opens a new browser window.
Syntax

window.open(URL, name, specs);

URL Optional. Specifies the URL of the page to open. If no URL is specified, a new
window with about:blank is opened

name Optional. Specifies the target attribute or the name of the window. The
following values are supported:

● _blank - URL is loaded into a new window. This is default


● _parent - URL is loaded into the parent frame
● _self - URL replaces the current page
● _top - URL replaces any framesets that may be loaded
● name - The name of the window (Note: the name does not specify the
title of the new window)

specs Optional. A comma-separated list of items, no whitespaces. The following


values are supported:

height=pixels The height of the window. Min. value is 100

left=pixels The left position of the window. Negative values not allowed

location=yes|no|1|0 Whether or not to display the address field. Opera only

menubar=yes|no|1|0 Whether or not to display the menu bar


resizable=yes|no|1|0 Whether or not the window is resizable. IE only

scrollbars=yes|no|1| Whether or not to display scroll bars. IE, Firefox & Opera only
0

status=yes|no|1|0 Whether or not to add a status bar

titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling

application is an HTML Application or a trusted dialog box

toolbar=yes|no|1|0 Whether or not to display the browser toolbar. IE and Firefox only

top=pixels The top position of the window. Negative values not allowed

width=pixels The width of the window. Min. value is 100

Close():
Used to close the current window.
Sy:
window.close();

Ex
<html>

<body>

<p>Click the button to open a new window called "MsgWindow" with some text.</p>

<button >

<button </button>

<script>

function myFunction() {
myWindow= window.open("", "_blank",
"toolbar=yes,scrollbars=yes,resizable=no,top=200,left=300,width=400,height=400");

myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px


tall!</p>");

function closeWin() {

myWindow.close();

</script>

</body>

</html>

16)MESSAGES AND CONFIRMATIONS:


Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example,
if one input field requires to enter some text but the user does not provide any input,
then as a part of validation, you can use an alert box to give a warning message.

An alert box can still be used for friendlier messages. Alert box gives only one button
"OK" to select and proceed.
Example
<html>

<head>

<script type = "text/javascript">

function Warn() {

alert ("This is a warning message!");

document.write ("This is a warning message!");

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>
<input type = "button" value = "Click Me" />

</form>

</body>

</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays
a dialog box with two buttons: OK and Cancel.

If the user clicks on the OK button, the window method confirm() will return true. If
the user clicks on the Cancel button, then confirm() returns false.
Example
<html>

<head>

<script type = "text/javascript">

function getConfirmation() {

var retVal = confirm("Do you want to continue ?");

if( retVal == true ) {

document.write ("User wants to continue!");

return true;

} else {

document.write ("User does not want to continue!");

return false;

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type = "button" value = "Click Me" />

</form>

</body>

</html>
Prompt Dialog Box

The prompt dialog box is very useful when you want to pop-up a text box to get user
input. Thus, it enables you to interact with the user. The user needs to fill in the field
and then click OK.
This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default string
to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the
window method prompt() will return the entered value from the text box. If the user
clicks the Cancel button, the window method prompt() returns null.
Example
<html>

<head>

<script type = "text/javascript">

function getValue() {

var retVal = prompt("Enter your name : ", "your name here");

document.write("You have entered : " + retVal);

</script>

</head>

<body>

<p>Click the following button to see the result: </p>

<form>

<input type = "button" value = "Click Me" />

</form>

</body>

</html>

17)status :

The status property sets the text in the status bar at the bottom of the browser, or
returns the previously set text.

window.status = "Some text in the status bar!!";

<html>

<head>
<script type="text/javascript">

function statwords(message)

window.status = message;

</script>

</head>

<center>

<form>

<input type="button" VALUE="Write a status bar message" >
is my message');">

<input type="button" VALUE="Erase the status bar message" >
');">

</form>

</center> </html>

18)Rollover Buttons:

A rollover button is a dynamic web button that changes appearance depending on the
location of the users mouse pointer. It contains three stages: normal, over and down.
The normal state appears when mouse is off the button , the over state applies when
your mouse rolls over the button, and the down state applies to when you click on the
button.
Rollover buttons come in different shapes , sizes, colors and styles. Rollover buttons
extend the normal functionality of a button.

onmouseenter The event occurs when the pointer is moved onto an element

onmousemove The event occurs when the pointer is moving while it is over an element

onmouseout The event occurs when a user moves the mouse pointer out of an
element, or out of one of its children
onmouseover The event occurs when the pointer is moved onto an element, or onto
one of its children

EX:
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
padding: 30px;
text-align: center;
background-color: lightseagreen;
}

p{
background-color: cyan;
}
</style>
<script>
function mouseover()
{
document.myimg.src="a.jpg";
}
function mouseout()
{
document.myimg.src="b.jpg";
}
var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
document.getElementById("demo").innerHTML = z+=1;
}

function myEnterFunction() {
document.getElementById("demo2").innerHTML = x+=1;
}
function myOverFunction() {
document.getElementById("demo3").innerHTML = y+=1;
}
</script>
<body>
<img src="b.jpg" name="myimg" width="200px" height="250px"
><div > <p>onmousemove: <br> <span id="demo">Mouseover me!</span></p>
</div>

<div > <p>onmouseenter:<br> <spanid="demo2">Mouseover me!</span></p>
</div>
<div > <p>onmouseover:<br> <span id="demo3">Mouse over me!</span></p>
</div>

</body>
</html>

19)MOVING IMAGE:

JavaScript can be used to move an image around the web page according to some sort
of pattern determined by a logical equation or function. In fact this is not a moving image
at all, that’s just the effect. What is actually moving is a layer of content.
To make an animation possible, the animated element must be animated relative to a
“parent container”. The container element should be created with
style=”position:relative|absolute”.
JavaScript provides the following function for this animation
setTimeout(function,duration)
The function calls function after duration milliseconds from now.
<HTML>
<script type="text/javascript">
var x=0;
function move()
{
document.a.style.marginLeft=x+"%";
x=x+10;
if(x==100)
x=0;
var t=setTimeout("move()",500);

}
</script>
<BODY >

<IMG SRC="a.jpg" WIDTH="100" HEIGHT="100" name='a' BORDER="1" ALT="">

</BODY>
</HTML>

Ex-2

<html>
<script type="text/javascript">
function moveleft()
{
document.getElementById('image').style.position="absolute";
document.getElementById('image').style.left="0";
}
function moveback()
{
document.getElementById('image').style.position="absolute";
}

</script>
<body>
<img id="image" src="./face.gif"
> />

</body>
</html>

20)WRITING IN TO DIFFERENT FRAMES:


Today, most of the web browsers support frames , which enable you to divide the
browser window into multiple pages. Each frame can contain a separate URL or the
output of a script.
Most of the client-side JavaScript applications involve only a single window or frame.
In the real world .JavaScript applications often involve multiple windows or frames.
When a window contains multiple frames, each frame 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 objects name is the same as the NAME attribute you given
in the <frame> tag.
Remember the window and self keywords , which refer to the current window? When
you are using frames, these keywords refer to the current frame instead. Another
keyword, parent ,enables you to refer to the main window.
Save it as color.html
<html>
<head>
<title>Color page</title>
</head>
<frameset rows="60%,40%">
<frame src="main.html" name="topone">
<frame src="blank.html" name="botone">
</frameset>
</html>
Save it as blank.html
<html>
<head>
<title>blank</title>
</head><body> </body> </html>
Save it as color.html
<html>
<head>
<script language="javascript" type="text/javascript">
function showit()
{
var topbox=document.forms[0].elements;
var bottombox=parent.frames['botone'].document;
var bg=topbox.bgcol.value;
var fg=topbox.fgcol.value;
var thc=topbox.thcol.value;
var tdc=topbox.tdcol.value;
bottombox.open();
bottombox.write("<body bgcolor="+bg+"text="+fg+">\n");
bottombox.write("<h1 align=center>The Result Is</h1>");
bottombox.write("<table align=center border=2"
+"cellspacing=4>\n<tr>"
+"<th>Plain Heading</th>"
+"<th bgcolor="
+thc
+"> Colored Heading</th>"
+"</tr>"
+"<th>Plain Data</th>"
+"<th bgcolor="+tdc+">Colored Data</th>"
+"</tr>" +"</tr>\n</table>");
bottombox.write("</body>");
bottombox.close();
}
</script>
</head>
<body text="red">
<h1 align="center">Color Program</h1>
<form>
<table align="center">
<tr>
<td colspan="4" align="center">
<h2>Enter the color value in the box</h2>
</td>
</tr>
<tr>
<td><h3>Back ground color</h3></td>
<td><input type="text" size="16" name="bgcol" value="white">
</td>
<td><h3>Text color</h3></td>
<td><input type="text" size="16" name="fgcol" value="black">
</td>
</tr>
<tr>
<td><h3>Table Heading</h3></td>
<td><input type="text" size="16" name="thcol" value="black">
</td>
<td><h3>Table Data</h3></td>
<td><input type="text" size="16" name="tdcol" value="black">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="Showit" ></td>
<td colspan="2" align="center">
<input type="reset" value="resetit">
</td>
</tr>
</table>
</form>
</body>
</html>

When a frameset is loaded into the main window a frame tree is created. The
window, which JavaScript calls top, holds some frames underneath it. If these frames
have nested framesets inside themselves, then a further level is added to the tree. A
page with frames set up as on the left will have a frame tree as on the right:

You might also like