0% found this document useful (0 votes)
10 views41 pages

Web Interface Unit 3

The document provides an overview of Dynamic HTML (DHTML) and JavaScript, explaining how DHTML combines HTML, CSS, and JavaScript to create interactive web pages. It covers JavaScript's applications, variable types, scopes, string manipulations, mathematical functions, and various programming statements. Additionally, it highlights the differences between variable declarations using var, let, and const, along with examples of JavaScript syntax and functions.

Uploaded by

Magam Vijitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views41 pages

Web Interface Unit 3

The document provides an overview of Dynamic HTML (DHTML) and JavaScript, explaining how DHTML combines HTML, CSS, and JavaScript to create interactive web pages. It covers JavaScript's applications, variable types, scopes, string manipulations, mathematical functions, and various programming statements. Additionally, it highlights the differences between variable declarations using var, let, and const, along with examples of JavaScript syntax and functions.

Uploaded by

Magam Vijitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT – III

DHTML:
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user. DHTML
included JavaScript along with HTML, CSS and DOM to make the page dynamic. HTML was used to
create a static page. It only defined the structure of the content that was displayed on the page. With
the help of CSS, we can beautify the HTML page by changing various properties like text size,
background color, etc. The HTML and CSS could manage to navigate between static pages but couldn’t
do anything else.
This combo made the web pages dynamic and eliminated the problem of creating static pages for
each user. In DOM, the document is represented as nodes and objects which are accessed by different
languages like JavaScript to manipulate the document.
Example DHTML:

<html><body>
<center><h1 id = "para1">
[Link]-BACHELOR OF SCIENCE</h1>
<input type = "Submit" onclick =
"Click()" ></center>
<script>
function Click() {
[Link]("para1").[Link]
or = "blue";
}
</script>
</body></html>

***JAVA SCRIPT:
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language. It can be
used for both Client-side as well as Server-side developments. JavaScript also known as a scripting
language for web pages. JavaScript contains a standard library of objects, like Array, Date, and Math,
and a core set of language elements like operators, control structures, and statements.
JavaScript can be added to your HTML file in two ways:
 Internal JavaScript
 External JavaScript
Internal JavaScript: We can add JS code directly to our HTML file by writing the code inside the <script>
& </script>. The <script> tag can either be placed inside the <head> or the <body> tag according to the
requirement.
Example:
<html> <head> <title>
Basic Example to Describe JavaScript
</title> </head>
<body> <script>
[Link]("Welcome to Java Script");
</script> </body> </html>
External JavaScript: We can create the file with a .js extension and paste the JS code inside of it. After
creating the file, add this file in <script src=”file_name.js”> tag, and this <sctipt> can import inside
<head> or <body> tag of the HTML file.
Example:
<html > <head> <title> alert("Welcome to Java Script");
Basic Example to
Describe JavaScript
</title>
<script
src="[Link]"></script>
</head> <body>
</body> </html>

****APPLICATIONS OF JAVASCRIPT:
 Creating Interactive Websites: JavaScript is used to make web pages dynamic and interactive.
It means using JavaScript, we can change the web page content and styles dynamically. 
 Building Applications: JavaScript is used to make web and mobile applications. To build web
and mobile apps, we can use the most popular JavaScript frameworks like – ReactJS, React
Native, [Link] etc.
 Web Servers: We can make robust server applications using JavaScript. To be precise we use
JavaScript frameworks like [Link] and [Link] to build these servers.
 Game Development: JavaSCript can be used to design Browser games. In JavaScript, lots of
game engines are available that provide frameworks for building games. 
**VARIABLES IN JAVASCRIPT: Variables in JavaScript are containers that hold reusable data. It
is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location. 
 In JavaScript, all the variables must be declared before they can be used.
JavaScript variables were solely declared using the var keyword followed by the name of the variable
and semi-colon.
Syntax: var var_name;
Example: var x;
The var_name is the name of the variable which should be defined by the user and should be unique.
These types of names are also known as identifiers.
The rules for creating an identifier in JavaScript are:
 The name of the identifier should not be any pre-defined word(known as keywords)
 The first character must be a letter, an underscore (_), or a dollar sign ($).
 Subsequent characters may be any letter or digit or an underscore or dollar sign.
var name; // Declaring single variable
var name, title, num; // Declaring multiple variables
var name = "Harsh"; // Initializing variables

var num = 5; // Creating variable to store a number


num = "Computer Science"; // Store string in the variable num
The above example executes well without any error in JavaScript, unlike other programming
languages.
we have two new variable containers: let and const. The variable type Let shares lots of similarities
with var but unlike var, it has scope constraints.
var and let are both used for variable declaration in javascript but the difference between them is
that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and
must be declared before use whereas variables declared with var keyword are hoisted.
Example 1 Example 2:
[Link](x);
[Link](x);
var x=5;
[Link](x); let x=5;
Output: [Link](x);
undefined
Output:
5
ReferenceError: Cannot access 'x' before initialization

----In the following code, clicking start will call a function that changes the color of the two headings
every 0.5sec. The color of the first heading is stored in a var and the second one is declared by using
let. Both of them are then accessed outside the function block. Var will work but the variable declared
using let will show an error because let is block scoped.
<HTML><BODY>
<h1 id="var" style="color:black;">COMPUTER SCIENCE</h1>
<h1 id="let" style="color:black;">COMPUTER SCIENCE</h1>
<button id="btn" onclick="colour()">Start</button>
<script type="text/javascript">
function colour() {
setInterval(function() {
if ([Link]('var').[Link] == 'black')
var col1 = 'blue';
else
col1 = 'black';

if ([Link]('let').[Link] == 'black') {
let col2 = 'red';
} else {
col2 = 'black';
}
[Link]('var').[Link] = col1;
[Link]('let').[Link] = col2;
}, 500);
}
</script></BODY></HTML>
Output:
Const is another variable type assigned to data whose value cannot and will not change throughout
the script.
// const variable
const name = 'Mukul';
name = 'Mayank'; // will give Assignment to constant variable error.

In JavaScript, there are two types of scopes:


1. Global Scope – Scope outside the outermost function attached to the window.
2. Local Scope – Inside the function being executed.
**STRING MANIPULATIONS:
JavaScript strings are for storing and manipulating text. A JavaScript string is zero or more characters
written inside quotes.
In JavaScript, all strings are represented as instances of the String object. The String
object is wrapper class and member of global objects. String object used to perform
operations on the stored text, such as finding the length of the string, searching for
occurrence of certain characters within string, extracting a substring etc.,
[Link] quotes(‘ ‘) or
double quotes(“ “)

var string1= “ Ques10“;

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";
example of creating string literal.
<script>
var str="This is string literal";
[Link](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");
example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
[Link](stringname);
</script>
String object methods:
Methods Description
charAt() It provides the char value 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
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
toUpperCase() It converts the given string into uppercase letter.
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.

***MATHEMATICAL FUNCTIONS:
The JavaScript Math is a built-in object that provides properties and methods for
mathematical constants and functions to execute mathematical operations. It is not a
function object, not a constructor. You can call the Math as an object without creating it
because the properties and methods of Math are static.
•The Math object is used to perform simple and complex arithmetic operations.

•The Math object provides a number of properties and methods to work with Number

values

•The Math object does not have any constructors. All of its methods and properties are

static; that is, they are member functions of the Math object itself. There is no way to

create an instance of the Math object.

Properties of Math object


o PI - The value of Pi
o E - The base of natural logarithm
o LN2 - Natural logarithm of 2
o LN10 - Natural logarithm of 10
o LOG2E - Base 2 logarithm of e
o LOG10E - Base 10 logarithm of e
o SQRT2 - Square root of2
o SQRT1_2 - Square root of½
syntax for Math property: [Link].

Example: [Link]; // returns 3.141592653589793

Methods of Math object

max(a,b) - Returns largest of a and b

min(a,b) - Returns least of a and b

round(a) - Returns nearest integer

ceil(a) - Rounds up. Returns the smallest integer greater than or equal to a

floor(a) - Rounds down. Returns the largest integer smaller than or equal toa

exp(a) – Returns --- ea

pow(a,b) – Returns --- ab

abs(a) - Returns absolute value of a

random() - Returns a pseudo random number between 0 and1

sqrt(a) - Returns square root of a

sin(a) - Returns sin of a (a is in radians)

cos(a) - Returns cos of a (a is in radians)

syntax for Math any methods is : [Link].(number)

Example: [Link](x) returns the nearest integer:

[Link](4.9); // returns 4

[Link](8, 2); // returns 64

[Link](64); // returns 8

[Link](0, 150, 30, 20, -8, -200); // returns 150


**JAVA SCRIPT STATEMENTS:
The programming instructions written in a program in a programming language are
known as statements. The order of execution of Statements is the same as they are
written.
1. Semicolons:
 Semicolons separate JavaScript statements.
 A semicolon marks the end of a statement in javascript.
<script>
let a, b, c;
a = 2;
b = 3;
c = a + b;
[Link](“sum”+c);
</script>
Multiple statements on one line are allowed if they are separated with a semicolon.
a=2;b=3;z=a+b;
2. Code Blocks: JavaScript statements can be grouped together inside curly brackets.
Such groups are known as code blocks. The purpose of grouping is to define statements
to be executed together.
Example: JavaScript function
<script>
function myFunction() {
let a, b, c;
a = 2;
b = 3;
c = a + b;
[Link](“sum”+c);
}
</script>
3. White Space: Javascript ignores multiple white spaces.
<script>
[Link](10 * 2);
[Link]( 10 * 2);
<!-- namespace do not make difference -->
</script>
4 Keywords: Keywords are reserved words and cannot be used as a variable name. A
Javascript keyword tells about what kind of operation it will perform.

Some commonly used keywords are:

 break and continue: break keyword is used to terminate a loop and continue is
used to skip a particular iteration in a loop and move to the next iteration.

var i; var i;
for (i = 1; i < 5; i++) { for (i = 1; i < 5; i++) {
if (i ==3) { if (i ==3) {
break; continue;
} }
[Link](i); [Link](i);
} }
Output: 1 2 Output: 1 2 4

 while: A While Loop in Javascript is a control flow statement that allows the code
to be executed repeatedly based on the given boolean condition.
There are mainly two types of loops:
i)Entry Controlled loops: In this type ii)Exit Controlled Loops: In this
of loop, the test condition is tested type of loop the test condition is
before entering the loop tested or evaluated at the end of the
body. ForLoop and While Loops are loop body. Therefore, the loop body
entry-controlled loops. will execute at least once, irrespective
of whether the test condition is true
Syntax: or false. the do-while loop is exit
while (condition) { controlled loop.
// Statements
} Syntax:
do {
// Statements
}
while (condition);

 for: It helps in executing a block of statements till the condition is true.

Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Statement 1: It is the initialization of the counter. It is executed once before the
execution of the code block.
Statement 2: It is the testing statement that defines the condition for executing the
code block It must return a boolean value. It is also an entry-controlled loop as the
condition is checked before the execution of the loop statements.
Statement 3: It is the increment or decrement of the counter & executed (every
time) after the code block has been executed.

for/in loop: There is another advanced loop called for/in loop which runs through all
the properties of an object.
Syntax :
for (var in object) { statements to be executed };
Ex:
var numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
[Link](x+”\n”);
}

For of:The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings
Syntax
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the
variable. Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.
const cars = ["BMW", "Volvo", "Mini"];
for (let x of cars) {
[Link](x+”\n”);
}
 function: This keyword is used to declare a function.

 return: This keyword is used to exit a function.

 switch: This helps in executing a block of codes depending on different cases.

 var, let, and const: These keywords are used to declare a variable in js.

**OPERATORS:
JavaScript operators operate the operands, these are symbols that are used to
manipulate a certain value or operand. Operators are used to performing specific
mathematical and logical computations on operands.

JavaScript Operators: There are various operators supported by JavaScript.


 JS Arithmetic Operators
 JS Assignment Operators
 JS Comparison Operators
 JS Logical Operators
 JS Ternary Operators
 JS Bitwise Operators
 JS typeof Operator
***ARRAYS IN JAVA SCRIPT:

•Multiple values are stored in a single variable using the Array object.

•In JavaScript, an array can hold different types of data types in a single slot, which
implies that an array can have a string, a number or an object in a single slot.

An Array object can be created by using following ways:

(i) Using the Array Constructor: To create empty array when don’t know the exact
number of elements to be inserted in an array.
var arrayname = new Array();

To create an array of given size: var arrayname = new Array(size);

To create an array with given elements:

var arrayname = new Array(“element1”,”element2”,…”element n”);

(ii) Using the Array Literal Notation:


To create empty array: Var arrayname=[];

To create an array when elements are given:

var arrayname=[“element 1”,”element 2”,…..,”element n”];

Methods of the Array object:

o reverse() - Reverses the array elements

o concat() - Joins two or more arrays

o sort() - Sort the elements of an array

o push() - Appends one or more elements at the end of an array


o pop() - Removes and returns the last element

o shift() - Removes and returns the first element

***FUNCTIONS IN JAVASCRIPT
A function is a set of statements that take inputs, do some specific computation, and
produce output.
A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
Example
Calculate the product of two numbers, and return the result:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same
code many times with different arguments, to produce different results.
***JavaScript Objects:

A JavaScript object is an entity having state and behaviour (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc., JavaScript is an object-
based language. Everything is an object in JavaScript. JavaScript is template based not
class based. Here, we don't create class to get the object. But, we direct create objects.

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

Syntax:

object={property1:value1, property2:value2, propertyN:valueN};

As you can see, property and value is separated by : (colon).

Example:

<html> <body> <script>

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

[Link]([Link]+" "+[Link]+" "+[Link]);

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

Output:

102 Shyam Kumar 40000

2) By creating instance of Object

Syntax: var objectname=new Object();

Here, new keyword is used to create object.

Example:

<html><body><script> var emp=new Object(); [Link]=101;

[Link]="Ravi Malik"; [Link]=50000;

[Link]([Link]+" "+[Link]+" "+[Link]);


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

Output of the above example

101 Ravi 50000

3) By using an Object constructor

Here, you 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.

Example:

<html><body><script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script></body></html>
Output of the above example
103 Vimal Jaiswal 30000

***Regular Expressions:
The term Regex stands for Regular expression. The regex or regexp or regular
expression is a sequence of different characters which describe the particular search
pattern. It is also referred/called as a Rational expression. It is mainly used for searching
and manipulating text strings. In simple words, you can easily search the pattern and
replace them with the matching pattern with the help of regular expression.
This concept or tool is used in almost all the programming or scripting languages such
as PHP, C, C++, Java, Perl, JavaScript, Python, Ruby, and many others. It is also used
in word processors such as word which helps users for searching the text in a document,
and also used in various IDEs. The pattern defined by the regular expression is applied
to the given string or a text from left to right.
Regular Expression Characters
1. Metacharacters
2. Quantifier
3. Groups and Ranges
4. Escape Characters or character classes
^ This character is used to match an ^a is an expression match to the string
expression to its right at the start of which starts with 'a' such as "aab",
a string. "a9c", "apr", "aaaaab", etc.
$ The $sign is used to match an r$ is an expression match to a string
expression to its left at the end of a which ends with r such as "aaabr", "ar",
string. "r", "aannn9r", etc.,
. This character is used to match any b.x is an expression that match strings
single character in a string except the such as "bax", "b9x", "bar".
line terminator, i.e. /n
| It is used to match a particular a|b is an expression which gives
character or a group of characters on various strings, but each string
either side. If the character on the left contains either a or b.
side is matched, then the right side's
character is ignored.
\ It is used to escape a special
character after this sign in a string.

A It is used to match the character 'A' This expression matches those strings
in the string. in which at least one- time A is
present. Such strings are "Amcx",
"mnAr", "mnopAx4".

1. Metacharacters
Characters Description Example

() It is used to match everything which is in A(xy) is an expression which matches


the simple bracket. with the following string: "Axy"

{ } It is used to match a particular number of xz{4,6} is an expression which matches


occurrences defined in the curly bracket for with the following string: "xzzzzz"
its left string.

[ ] It is used to match any character from a xz[atp]r is an expression which matches


range of characters defined in the square with the following strings: "xzar",
bracket. "xztr", and "xzpr"

[pqr] It matches p, q, or r individually. Following strings are matched with this


expression:

"p", "q", and "r".

[^…..] It matches a character Suppose, Ab[^pqr] is an expression


which is not defined in the which matches only the following string:
square bracket. "Ab"

[a-z] It matches letters of a small case from a to This expression matches the strings such
z. as:

"a", "python", "good".

[A-Z] It matches letters of an upper case from A This expression matches the strings such
to Z. as:

"EXCELLENT", "NATURE".

[0-9] It matches a digit from 0 to 9. This expression matches the strings such
as:

"9845", "54455"

[aeiou] This square bracket only matches the small -


case vowels.

[AEIOU] This square bracket only matches the -


upper-case vowels.

ab[^4-9] It matches those digits or characters which This expression matches those strings
are not defined in the square bracket. which do not contain 5, 6, 7, and 8.

Quantifiers
Description Example
+ This character specifies an expression s+ is an expression which gives
to its left for one or more times. "s", "ss", "sss", and so on.
? This character specifies an expression aS0? is an expression which gives
to its left for 0 (Zero) or 1 (one)times either "a" or "as", but not "ass".
* This character specifies an expression Br* is an expression which gives "B",
to its left for 0 or more times "Br", "Brr", "Brrr", and so on…
{x} It specifies an expression to its left for Mab{5} is an expression which gives
only x times. the following string which contains 5
b's: "Mabbbbb"
{x,y} It specifies an expression to its left, at Pr{3,6}a is an expression which
least x times but less than y times. provides twostrings. Bothstrings are
as follows: "Prrrr" and "Prrrrr"
The quantifiers are used in the regular expression for specifying the number of
occurrences of a character.
Groups and Ranges
The groups and ranges in the regular expression define the collection of characters
enclosed in the brackets.
Escape Characters or Character Classes
Characters Description
\s It is used to match a one white space character
\S It is used to match one non-white space character.
\0 It is used to match a NULL character.
\a It is used to match a bell or alarm.
\d It is used to match one decimal digit, which means from 0 to 9
\D It is used to match any non-decimal digit.
\n It helps a user to match a new line.
\w It is used to match the alphanumeric [0-9a-zA-Z]
characters.
\W It is used to match one non-word character
\b It is used to match a word boundary.
For example:a regular expression that matches any string that begins with "Mr.".
// Literal syntax var regex = /^Mr\./;
// Constructor syntax var regex = new RegExp("^Mr\\.");
Note: When using the constructor syntax, you've to double-escape special characters,
which means to match "." you need to write "\\." instead of "\.". If there is only one
backslash, it would be interpreted by JavaScript's string parser as an escaping character
and removed.
Example:
var regex = /ca[kf]e/g;
var str = "He was eating cake in the cafe.";
var matches = [Link](regex);
alert([Link]); // Outputs: 2
***Exception Handling in JavaScript
An exception signifies the presence of an abnormal condition which requires special
operable techniques. In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require specialized programming
constructs for its execution.
What is Exception Handling
In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them. It also enables to handle the flow
control of the code/program. For handling the code, various handlers are used that
process the exception and execute the code. For example, the Division of a non-zero
value with zero will result into infinity always, and it is an exception. Thus, with the help
of exception handling, it can be executed and handled.
A throw statement is used to raise an exception. It means when an abnormal condition
occurs, an exception is thrown using throw.
The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.
Thus, in a programming language, there can be different types of errors which may
disturb the proper execution of the program.
Types of ErrorsWhile coding, there can be three types of errors in the code:
1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a

programming language, a syntax error may appear.


2. Runtime Error: When an error occurs during the execution of the program, such an

error is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program

that may not produce the desired output, and may terminate abnormally. Such an error
is known as Logical error.
Error Object:When a runtime error occurs, it creates and throws an Error object. Such
an object can be used as a base for the user-defined exceptions too. An error object has
two properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
Built-in error types :
1. EvalError: It creates an instance for the error that occurred in the eval(), which is a
global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.

3. RangeError: It creates an instance for the error that occurs when a numeric variable

or parameter is out of its valid range.


4. ReferenceError: It creates an instance for the error that occurs when an invalid

reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an
error.
7. URIError: An instance is created for the error that occurs when invalid parameters

are passed in encodeURI() or decodeURI().


Exception Handling Statements
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
A try…catch is a commonly used statement in various programming languages. Basically,
it is used to handle the error-prone part of the code. It initially tests the code for all
possible errors it may contain, then it implements actions to tackle those errors (if occur).
A good programming approach is to keep the complex code within the try…catch
statements.
try{} statement: Here, the code which needs possible error testing is kept within the
try block. In case any error occur, it passes to the catch{} block for taking suitable
actions and handle the error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined exception
handler or the built- in handler. This block executes only when any error-prone code
needs to be handled in the try block. Otherwise, the catch block is skipped.
Syntax:
try{
expression;
} //code to be written.
catch(error){
expression; } // code for handling the error.
try…catch example:
<html> <head> Exception Handling</br></head>
<body> <script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
[Link](a); // displays elements of a
[Link](b); //b is undefined but still trying to fetch its value. Thus catch block
will be invoked
}
catch(e){
alert("There is error which shows "+[Link]); //Handling error
}
</script></body></html>
Throw Statement:Throw statements are used for throwing user-defined errors. User
can define and throw their own custom errors. When throw statement is executed, the
statements present after it will not execute. The control will directly pass to the catch
block.
try…catch…throw: syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
The exception can be a string, number, object, or boolean value.
throw example with try…catch
<html> <head>Exception Handling</head>
<body><script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
[Link]([Link]); // This will generate an error message
}</script></body></html>
try…catch…finally statements: Finally is an optional block of statements which is
executed after the execution of try and catch statements. Finally block does not hold for
the exception to be thrown. Any exception is thrown or not, finally block code, if present,
will definitely execute. It does not care for the output too.
Syntax:
try{
expression;
}
catch(error){
expression;
}
finally{
expression; } //Executable code
try…catch…finally example
<html> <head>Exception Handling</head><body><script>
try{
var a=2;
if(a==2)
[Link]("ok");
}
catch(Error){
[Link]("Error found"+[Link]);
}
finally{
[Link]("Value of a is 2 ");
} </script></body></html>
***JavaScript Events
The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the
browser. When javascript code is included in HTML, js react over these events and allow
the execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers. For example, when a user clicks over the
browser, add js code, which will execute the task to be performed on the event. Some of
the HTML events and their event handlers are:
Mouse events:
Event Event Description
Performed Handler
Click Onclick When mouse click on an element
Mouseover Onmouseover When the cursor of the mouse comes over the
element
Mouseout Onmouseout When the cursor of the mouse leaves an element
Mousedown onmousedown When the mouse button is pressed over the
element
Mouseup Onmouseup When the mouse button is released over the
element
Mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description
Keydown&Keyup Onkeydown When the user press and then release the key
Onkeyup
Form events:
Event Event Description
Performed Handler
Focus Onfocus When the user focuses on an element
Submit Onsubmit When the user submits the form
Blur Onblur When the focus is away from a form element
Change Onchange When the user modifies or changes the value of a form
element
Window/Document events
Event Event Handler Description
Performed
Load Onload When the browser finishes the loading of the page
Unload Onunload When the visitor leaves the current webpage, the browser
unloads it
Resize Onresize When the visitor resizes the window of the browser

Click Event example:


<html> <head> Javascript Events </head>
<body> <script language="Javascript" type="text/Javascript">
function clickevent(){
[Link]("<center> <h1>This is PB SIDDHARTHA COLLEGE OF ARTS &
SCIENCE");
}
</script> <form><input type="button" onclick="clickevent()" value="Who's this?"/>
</form> </body> </html>
Output:

Mouse Over Event


<html> <head>Event handling</head>
<body> <script language="Javascript" type="text/Javascript">
function clickevent(){
[Link]("<center><h1>This is PB SIDDHARTHA COLLEGE OF ARTS &
SCIENCE");
}
</script> <form>
<input type="button" onmouseover="clickevent()" value="Who's this?"/>
</form> </body> </html>
Output:
Focus Event:
<html> <head> Javascript Events</head> <body><h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/><script>
function focusevent(){
[Link]("input1").[Link]=" aqua";
}
</script></body></html>
Output:
Keydown Event example:
<html> <head> Javascript Events</head>
<body> <h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>function keydownevent(){
[Link]("input1"); alert("Pressed a key");
}
</script> </body> </html>
Output:

Load event
<html> <head>Javascript Events</head>
<body onload="[Link]('Page successfully loaded');">
<script>[Link]("The page is loaded successfully"); </script>
</body></html>
Output:

***JavaScript Form Validation


1. JavaScript form validation
2. JavaScript email validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation. Most of the web developers prefer JavaScript form
validation. Through JavaScript, we can validate name, password, email, date, mobile
numbers and more fields.
Example for form validation:
To validate the name and password. The name can’t be empty and password can’t be
less than 6 characters long. Here, we are validating the form on form submit. The user
will not be forwarded to the next page until given values are correct.

i) Password checking:
<html><head><script>
function validateform()
{
var name=[Link];
var password=[Link];
if (name==null ||name=="") {
alert("Name can't be blank");
return false;
}

else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
} }
</script></head><body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register"> </form></html>
Output:

ii) Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<html><script>
function validate(){
var num=[Link];
if (isNaN(num)){
Alert(“Enter Nnumeric value only”);
return false;
}
else
{
return true;
} }
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num ><br/><input type="submit"
value="submit">
</form></body></html>

2. Email validation
We can validate the email by the help of JavaScript. There are many criteria that need
to be follow to validate the email id such as:
o email id must contain the @ and . character
o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.
<html><script>
function validateemail(){
var x=[Link]; var
atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid email address”);
return false;
}}
</script> <body>
<form name="myform" method="post" action="[Link]" onsubmit="return
validateemail();"> Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form> </body></html>
Output:
**JavaScript Window open method
JavaScript offers in-built methods to open and close the browser window to perform
additional operations like robot window etc. These methods help to open or close the
browser window pop- ups. Following are the window methods:open()
The [Link] method is used to open a new web page into a new
window and [Link] method to close web page opened by [Link] method.
See the [Link]() method in detail:
[Link]():
It is a pre-defined window method of JavaScript used to open the new tab or window in
the browser. This will depend on your browser setting or parameters passed in the
[Link]() method that either a new window or tab will open.
This method is supported by almost all popular web browsers, like Chrome, Firefox, etc.
Following is the syntax and parameters of the window open method -
Syntax:
This function accepts four parameters, but they are optional.
1. [Link](URL, name, specs, replace); Or
You can also use this function without using the window keyword as shown below:
1. open(URL, name, specs, replace)
There is no difference between both syntaxes.
Parameters List
Below is the parameters list of [Link]() method. Note that - all parameters of this
method are optional and works differently.
URL: This optional parameter of the [Link]() function contains the URL string of
a webpage, which you want to open. If you do not specify any URL in this function, it will
open a new blank window (about:blank).
name: Using this parameter, you can set the name of the window you are going to open.
Return Values
It will return a newly opened window.
Examples
Here are some examples of [Link]() function to open the browser window/tab. By
default, the specified URL opens in new tab or window. See the examples below:
1. open() with URL parameter
This is a simple example of window open method having a website URL inside it. We have
used a button. By clicking on this button, [Link]() method will call and open the
website in new browser tab.
Example: [Link]() with parameters
<html>
<body><center>
<h1>PB Siddhartha college of Arts and Science</h1>
<br><br>click here for ag & sg website<br>
<input type=button value="ag&sg"
onclick=[Link]("[Link]
</center></body></html>
output:

[Link]() without parameters


In this example, we will not pass any parameter to [Link]() function so that the
new tab will open in previous window.
<html> <body> Click the button to open new window <br><br>
<button onclick="[Link]()"> Open Window </button> </body></html>
When you will execute the above code, a button will appear with it.

When you click this Open Window button, a blank window will open in a new tab.

Define the size for the new window:In this example, we will specify the height and
width for the new window. For this, we will use the third parameter (specs) in
[Link]() method and pass the height and width of the window separated by a
comma to this function. So, the window will open in the specified size.
<html><body><center>
<h1>Ag and Sg Siddhartha Degree college of Arts and Science</h1>
<br><br>click here for ag & sg website<br>
<button onclick=[Link](“[Link] ”height=100”,
”width=100”)>
ag & sg</button> </center></body></html>
Output: Execute the above code and get the output as given below. This will contain a
button to click and open the new URL on the same parent window.

When you click this button, a new window of pb Siddhartha college website will open
under the parent window of size.
**Messages and Conformations in JavaScript
Managing messages and conformations are one of the major task of Dynamic
programming. While handing event derive process also the user need to conforms some
actions and Those can be achieved using three JavaScript popup boxes.
The Alert Box:
An alert box is often used if you want to make sure information comes throw to the user.
When an alert box popup, the user will have to click “ok”.
Syntax::: alert(” some text Here”);
Example:
<html><head><script type="text/javascript">
function show_alert(){
alert(" I am an alert box !");
}</script>
</head><body><button onClick="show_alert()">show alert box</button>
</body></html>
Output:

The Confirm Box


A confirm box is often used if you want the user to verify or accept something. When a
confirm box popup, The user will have click either “ok” or “cancel” to processed. If the
user click “OK” , the box returns true otherwise false.
Syntax: confirm(” some text”);
Example:
<html> <head><script type="text/javascript">
function show_confirm()
{
var r=confirm(" press a button");
if(r==true)
{
alert(" you have pressed ok!");
}
else
{
alert(" You have pressed cancel !");
}
}
</script></head><body>
<input type="button" onClick="show_confirm()" value=confirm message"/>
</body></html>
Output:
The Prompt Box:
A prompt box often used if you want the user to input a value before entering a page.
When a prompt box popup, the user will have to click either “ok” or “cancel” to proceed
after entering an input value. If the user clicks “OK” the box returns the input value. If
the user clicks “cancel” the box returns null.
Syntax: prompt(” some text “,” default”);
Example:
<html><head>
<script type="text/javascript">
function show_prompt(){
var r=prompt(" Please enter your name");
if(r!=null){
[Link]("Hello "+ r +" ! how are you today");
}}
</script></head><body>
<input type="button"onClick="show_prompt()" value=show"/>
</body></html>
Output:
**JAVA SCRIPT STATUS BAR:
JavaScript gives you the ability to modify the status bar. For example it can be useful to
display information about a link, when the user moves his mouse over it or you can
display a small amount of information about the page the user is on in the status bar.
Status Bar Example:
<html> <head> <title>JavaScript Status Bar</title> </head>
<body onLoad="[Link]='Welcome PB Siddhartha College!';return true">
</body> </html>
Output:

***WRITING TO DIFFERENT FRAME (Window frames Property/dynamic


faming):
The frames property returns an array-like object, which represents all <iframe> elements
in the current window. The <iframe> elements can be accessed by index numbers. The
index starts at 0.
Syntax: [Link]
Return Value: Returns a reference to the Window object, representing all frames in
the current window
Example:
<html> <body>
<p>Click the button to loop through the frames on this page, and change the
location of every frame to “[Link]”.</p> <button
onclick="myFunction()">Try it</button><br><br>
<iframe src="[Link]
<iframe src="[Link]
<iframe src="[Link]
<script>
function myFunction() {
var frames = [Link];
var i;
for (i = 0; i < [Link]; i++)
{
frames[i].location = "[Link]
}}
</script></body></html>
Output:
***ROLLOVER BUTTON:
Rollover can be accomplished using text, buttons or images, which can be made to appear
when the mouse is rolled over an image. The user needs two images/buttons to perform
rollover action.
A rollover button is a dynamic Web button that changes appearance depending on the
location of the user's mouse pointer. It contains three states: normal, over and down.
The normal state appears when your 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.
Types and uses: Rollover buttons come in different shapes, sizes, colours and styles.
Since images can be converted to rollover buttons, a rollover button can also contain
images. A rollover button can be raised, sunken, flat or animated when a user clicks on
it.
Rollover buttons are used primarily as navigational buttons on a Web page to direct
people to other locations. They are also used in drop-down and pop-up menus. Other
rollover buttons are used for animated effects and sounds, so an image, colour, shape,
text or sound can change as the user rolls over the button on the Web.
Benefits:
Rollover buttons extend the normal functionality of a button. Not only are they visually
attractive, but rollover buttons are also dynamic, altering the user to the fact that they're
active elements on the page. Web designers can add sound effects that will play if a user
moves his mouse over these buttons. When used in drop-down or pop-up menus, rollover
buttons help save navigational space.
Suggested Size:
The file size of a rollover button should be small. Since rollover buttons are images, they
can quickly take up extra space on the Web server and increase loading time.
Some of the key features of rollover include:
 Enables interaction between the user and the Web page
 Makes an image appear or disappear when the mouse is moved over it
 Makes a hidden image or element to appear when the mouse is moved over it
 Makes an element of the page change the color of the entire Web page when the
mouse is moved over it
 Causes text to pop up or become highlighted with bold colors when the mouse is
moved on a text element.
***MOVING IMGAES:
We can move an image to different location by using buttons. The present location of the
image can be collected by using offsetLeft and offsetTop values. To this value we will add
a step value which sets the new position of the image.
Example:
<html> <script type="text/javascript">
function moveleft(){
[Link]('image').[Link]="absolute";
[Link]('image').[Link]="0";
}
</script> <body><center>
<img id="image" src="C:\Users\dell\Desktop\[Link]" onclick="moveleft()"
height=50 width=50 /></body></html>

You might also like