Unit Ii Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 49

UNIT II

CLIENT SIDE PROGRAMMING

Java Script: An introduction to JavaScript–JavaScript DOM Model-Exception


Handling-Validation Built-in objects-Event Handling- DHTML with
JavaScript- JSON introduction – Syntax – Function Files
Java Script: An Introduction to Java
JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages. It is an interpreted, full-fledged programming
language that enables dynamic interactivity on websites when applied to an HTML
document.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments. JavaScript follows the syntax and structure of the C programming
language. Thus, it is a structured programming language.
2. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
3. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
4. It is a light-weighted and interpreted language.
5. It is a case-sensitive language.
6. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
7. It provides good control to the users over the web browsers.

Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.

Example

1 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


<html>

<body>

<h2>Welcome to JavaScript</h2>

<script>

document.write("Hello JavaScript by JavaScript");

</script>

</body>

</html>

3 Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

Between the body tag

<html>

<body>

<script type="text/javascript">

alert("Hello Javatpoint");

</script>

</body>

</html>

Between the head tag

<html>

2 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


<head>

<script type="text/javascript">

function msg(){

alert("Hello Javatpoint");

</script>

</head>

<body>

<p>Welcome to Javascript</p>

<form>

<input type="button" value="click" onclick="msg()"/>

</form>

</body>

</html>

External javascript
Message.js
function msg(){

alert("Hello Javatpoint");
}

HTML File
<html>
<head>

3 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Javascript Data Types

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

1. Primitive data type


2. 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:

1. var a=40;//holding number


2. 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


4 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Comment
 The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily
interpret the code.
Types of Comments

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment

 It is represented by double forward slashes (//). It can be used before and after the
statement.

 Example:

<html>

<body>

<script>

// It is single line comment

document.write("hello javascript");

</script>

</body>

</html>

JavaScript Multi line Comment

 It can be used to add single as well as multi line comments. So, it is more convenient.

5 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


 It is represented by forward slash with asterisk then asterisk with forward slash. For
example:

/* your code here */

Example:

<html>

<body>

<script>

/* It is multi line comment.

It will not be displayed */

document.write("example of javascript multiline comment");

</script>

</body>

</html>
JavaScript Variable

 A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript: local variable and global variable.

 There are some rules while declaring a JavaScript variable (also known as identifiers).

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.

Correct JavaScript variables

var x = 10;
var _value="sonoo";

Incorrect JavaScript variables

var 123=30;
var *aa=320;
Example Program
<html>
6 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>

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>

Or,

<script>
if(10<13){
var y=20;//JavaScript 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(){
7 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Java Script Output

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
 To access an HTML element, JavaScript can use the document.getElementById(id) method.
 The id attribute defines the HTML element. The innerHTML property defines the
HTML content

Example Using Inner HTML Output

<!DOCTYPE html> My First Web Page


<html>
My First Paragraph.
<body>
<h2>My First Web Page</h2> 11

<p>My First Paragraph.</p>


<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =5 + 6;
</script>
</body>
</html>

Using document.write()

Example Using document.write Output


8 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
My First Web Page
<!DOCTYPE html>
<html>
My first paragraph
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p> 11
<script>
document.write(5 + 6);
</script>
</body>
</html>

Using window.alert()

Example Using window.alert Output

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Using console.log()
 For debugging purposes, you can call the console.log() method in the browser to
display data.
Using console.log () Output
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>

Prompt Box

 A prompt box is often used if you want the user to input a value before entering a page.

9 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


 When a prompt box pops up, 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
 window.prompt("sometext","defaultText");
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4

5 <!-- Fig. 7.8: Addition.html -->


6 <!-- Addition Program -->
7

8 <html xmlns = "http://www.w3.org/1999/xhtml">


9 <head>
10 <title>An Addition Program</title>
11

12 <script type = "text/javascript">


13 <!--
14 var firstNumber, // first string entered by user
15 secondNumber, // second string entered by user
16 number1, // first number to add
17 number2, // second number to add
18 sum; // sum of number1 and number2
19

20 // read in first number from user as a string


21 firstNumber =
22 window.prompt( "Enter first integer", "0" );

10 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


JavaScript Operators
 JavaScript operators are symbols that are used to perform operations on operands.
 For example:
o var sum=10+20;
o Here, + is the arithmetic operator and = is the assignment operator.
11 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
 There are following types of operators in JavaScript.
o Arithmetic Operators
o Comparison (Relational) Operators
o Bitwise Operators
o Logical Operators
o Assignment Operators
o 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 (Remainder) 20%10 = 0

++ 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

12 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


< 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

13 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


+= 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.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.


Control Structure
 Control structure actually controls the flow of execution of a program.
 if … else
 switch case
 do while loop
 while loop
 for loop
JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.

14 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


1. if Statement
2. if else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.

if(expression){
//content to be evaluated
}
Example Output
<html>
<script>
function age()
{
if(document.getElementById("t1").value>=18)
{
window.alert("ELIGIBLE FOR VOTE")
}
}
</script>
<body>
<h1>Enter the age:<input
type="text"id="t1"><br></h1>
<button
type="button"onclick="age()">VERIFY</button>
</body>
</html>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

15 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


Example Output
<html>
<script>
function age()
{
if(document.getElementById("t1").value>=18)
{
window.alert("ELIGIBLE FOR VOTE");
}
else{
window.alert("NOT ELIGIBLE FOR VOTE");
}
}
</script>
<body>
<h1>Enter the age:<input type="text"id="t1"><br></h1>
<button type="button"onclick="age()">VERIFY</button>
</body>
</html>

JavaScript If...else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example Output
<html> a is equal to 20
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
16 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
Example Output
<!DOCTYPE html> B Grade
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;

17 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


default:
result="No Grade";
}
document.write(result);
</script>
</body>
</html>
JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}
Example Output
<!DOCTYPE html> 1
<html> 2
<body>
<script>
3
for (i=1; i<=5; i++) 4
{ 5
document.write(i + "<br/>")
}
</script>
</body>
</html>

JavaScript while loop

18 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}
Example Output
<!DOCTYPE html> 11
<html> 12
<body>
<script>
13
var i=11; 14
while (i<=15) 15
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>

JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The syntax
of do while loop is given below.

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

Example Output
<!DOCTYPE html> 21
<html> 22
<body>
<script>
23
var i=21; 24
do{ 25
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
19 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</html>

JavaScript for in loop

The JavaScript for in loop is used to iterate the properties of an object.


Syntax:
for(variable in object) {
// Code to be executed
}
Example Output
<!DOCTYPE html> Apple
<html lang="en"> Banana
<head>
<meta charset="utf-8">
Mango
<title>JavaScript Loop Through an Array Using For-In Loop</title> Orange
</head> Papaya
<body>
<script>
// An array with some elements
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Loop through all the elements in the array


for(var i in fruits) {
document.write("<p>" + fruits[i] + "</p>");
}
</script>
</body>
</html>
JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.

JavaScript Function Syntax

The syntax of declaring function is given below.


20 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
function functionName([arg1, arg2, ...argN]){
//code to be executed
}

JavaScript Functions can have 0 or more arguments.

Program Output
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>

JavaScript Function Arguments

Program Output
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Function with Return Value
Program Output
1. <script> hello javatpoint! How r u?
2. function getInfo(){
3. return "hello javatpoint! How r u?";
21 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>

JavaScript Array
 JavaScript array is an object that represents a collection of similar type of elements.
 There are 3 ways to construct array in JavaScript
o By array literal
o By creating instance of Array directly (using new keyword)
o By using an Array constructor (using new keyword)
1) JavaScript array literal:
Syntax: var arrayname=[value1,value2.....valueN];

Program Output
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

2) JavaScript Array directly (new keyword)

Syntax: var arrayname=new Array();


Program Output
<html> Arun
<body> Varun
<script> John
var i;
var emp = new Array();
emp[0] = "Arun";

22 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

3) JavaScript array constructor (new keyword)

 Create instance of array by passing arguments in constructor so that we don't have to


provide value explicitly.

Program Output
<html> Jai
<body> Vijay
<script> Smith
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

JavaScript DOM Model

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and
style of a document."

The W3C DOM standard is separated into 3 different parts:

23 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

DOM Programming Interface

 The HTML DOM can be accessed with JavaScript (and with other programming
languages).
 In the DOM, all HTML elements are defined as objects.
 The programming interface is the properties and methods of each object.
 A property is a value that you can get or set (like changing the content of an HTML
element).
 A method is an action you can do (like add or deleting an HTML element).

Example for DOM Programming Interface Output


<!DOCTYPE html> My First Page
<html>
<body>
Hello World!
<h2>My First Page</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
The getElementById Method

The most common way to access an HTML element is to use the id of the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The HTML DOM Document Object


Finding HTML Elements

Method Description

document.getElementById(id) Find an element by


element id

document.getElementsByTagName(name) Find elements by tag


name
24 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
document.getElementsByClassName(name) Find elements by class
name
Changing HTML Elements

Property Description

element.innerHTML = new html Change the inner HTML of an


content element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, Change the attribute value of an
value) HTML element
Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream


Changing HTML Content

 The easiest way to modify the content of an HTML element is by using the innerHTML property.
 To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

Example Changing the HTML Content Output


<html> New text!
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>

25 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


</html>

Changing the Value of an Attribute


• Syntax: document.getElementById(id).attribute = new value
Example Changing the Value of an Attribute Output
<!DOCTYPE html> JavaScript HTML DOM
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
document.getElementById("image").src = "landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to
landscape.jpg</p>
</body> The original image was smiley.gif, but
</html> the script changed it to landscape.jpg

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style

Program to Change the HTML Style Output


<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

Creating New HTML Elements (Nodes)


To add a new element to the HTML DOM, you must create the element (element node) first,
and then append it to an existing element.
<div id="div1">
<p id="p1">This is first paragraph.</p>
<p id="p2">This is second paragraph.</p>

26 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is third paragraph.");
para.appendChild(node);

var element=document.getElementById("div1");
element.appendChild(para);
</script>

This code creates a new <p> element:varpara = document.createElement("p");


To add text to the <p> element, create a text node first. This code creates a text node:
var node = document.createTextNode("This is a new paragraph.");
Then append the text node to the <p> element:para.appendChild(node);
Finally find the newly created element and append the to an existing element. This code
finds an existing element:
var element = document.getElementById("div1");
element.appendChild(para);
Removing existing HTML elements
 To remove an HTML element, find the parent of the element and then delete it
Replacing HTML Element
 The replaceChild() method replaces a child node with a new node.
 node.replaceChild(newnode, oldnode)

Parameter Description

newnode Required.
The node to insert.

oldnode Required.
The node to remove.

Java Script: Exception


Handling
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.

27 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


 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.

Types of Errors
While 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.

Types of Errors

1. RangeError: It creates an instance for the error that occurs when a numeric variable
or parameter is out of its valid range.
2. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
3. TypeError: When a variable is not a valid type, an instance is created for such an
error.
4. InternalError: It creates an instance when the js engine throws an internal error.

Exception Handling Statements

There are following statements that handle if any exception occurs:

o throw statements
o try…catch statements
o try…catch…finally statements.

JavaScript try and catch

 The try statement allows you to define a block of code to be tested for
errors while it is being executed.
 The catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.

28 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


Syntax
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}

Example for try and catch Output


<html> Exception Handling
<head> Exception Handling</br></head> 34,32,5,31,24,44,67
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(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 "+e.message); //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.

Syntax:
throw exception;
try…catch…throw syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
Example program for user-defined throw statement Output
<html> Exception Handling This is
<head>Exception Handling</head> the throw keyword
<body>
<script>
29 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
try {
throw new Error('This is the throw keyword'); //user-defined throw
statement.
}
catch (e) {
document.write(e.message); // 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.

Syntax
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}
Program for finally Output
<html> Exception Handling ok Value of a is 2
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
30 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</html>

Validation in JAVA SCRIPT

Form validation occurs at the server, after the client had entered all necessary data
and then pressed the Submit button. If some of the data that had been entered by the
client had been in the wrong form 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 is a lengthy process and over burdening 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 - Checking the form to make sure that the data entered is
right.

Data Format Validation – Checking the data entered in the form for right
value.
Program for Form Validation
<html><head>
<title>Form Validation</title>
<script type="text/javascript">
</script></head><body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right">Name</td>
<td><input type="text" name="Name" /></td></tr>
<tr><td align="right">EMail</td>
<td><input type="text" name="EMail" /></td></tr>
<tr><td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td></tr>
<tr><td align="right">Country</td><td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
31 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</select></td></tr>
<tr><td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr></table></form>
<script type="text/javascript"> function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
32 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
}
</script>
</body>

JAVA SCRIPT BUILT-IN OBJECTS

 Java Script has several built-in or native objects


 These objects can be accessed anywhere in the program as the other objects
 The following are some of the important JavaScript Native Objects:
 JavaScript Number Object
 Java Script Boolean Object
 Java Script String Object
 Java Script Array Object
 Java Script Date Object
 Java Script Math Object
JavaScript Number Object
The JavaScript number object enables you to represent a numeric value. It may be integer or
floating-point. JavaScript number object follows IEEE standard to represent the floating-
point numbers.
Number Properties

Property Description

MAX_VALUE The largest number possible in


JavaScript

MIN_VALUE returns the largest minimum value.


POSITIVE_INFINITY returns positive infinity, overflow value.
NEGATIVE_INFINITY returns negative infinity, overflow
value.
NaN represents "Not a Number" value.

33 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


Number Methods

Method Description

Number() Returns number object


toExponential() Returns a number written in exponential notation

toFixed() represents a number with exact digits after a decimal


point.

toString() It returns the given number in the form of string.

Example for Number Object Program


<html> 1.7976931348623157e+308
<head> 5e-324
</head>
<body>
<script>
document.writeln(Number.MAX_VALUE+"<br>")
;
document.writeln(Number.MIN_VALUE+"<br>");
</script>
</body>
</html>

Java script String object


 A string is a collection of characters.
Methods:
 concat (str)- This methods concatenates two strings (eg) st.concate(s2)
 charAt(index-val)- Returns the character at the specified index
 substring(begin,end)- This method returns the substring specified by begin and end
character
 toLowerCase()-It converts the given string into lowercase letter.
 toUpperCase()-It converts the given string into uppercase letter.
 valueOf()- returns the value of the string
Example for string object Output
<html>
<body>
<script>
var s1="hello";
var s2="vec";
document.write("first string:"+s1+"<br>");
document.write("concat:"+s1.concat(s2)+"<br>");
document.write("length:"+s1.length+"<br>");
34 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
document.write("character:"+s1.charAt(0)+"<br>");
document.write("uppercase:"+s1.toUpperCase()+"<br>");
</script>
</body>
</html>

Java script Array objects


 The array object is used to store multiple values in a single variable
 Example: var fruits = new Array(“apple”, “orange”, “mango”)
Methods
valueOf()- This method is used to obtain the primitive value of the array
push()- push the value in the array
pop()-is used to remove the value from the array
reverse()- This method is used to reverse the elements of an array
sort()- This method is used to sort elements of an array
splice()-The splice() method adds and/or removes array elements.
shift()-Shift (remove) the first element of the array
Example for array object Output
<html> array:10,20,30,40
<head> array:10,20,30,40,50
<body>
<script>
array:10,20,30,40
var a=new Array(10,20,30,40); array:40,30,20,10
document.writeln("array:"+a+"<br>"); array:30,20,10
a.push(50); array:10,20,30
document.writeln("array:"+a+"<br>"); array:10,20,30,11
a.pop();
document.writeln("array:"+a+"<br>");
a.reverse();
document.writeln("array:"+a+"<br>");
a.shift();
document.writeln("array:"+a+"<br>");
a.sort();
document.writeln("array:"+a+"<br>");
a.push(11);
</script>
</body>
</html>
Java Script Array splice()
Syntax
array.splice(index, howmany, item1, ....., itemX)
35 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
Parameter Description

index Required.
The position to add/remove items.
Negative value defines the position from the end of the array.

howmany Optional.
Number of items to be removed.

item1, ..., itemX Optional.


New elements(s) to be added.

Program for Splice() method Output


<!DOCTYPE html> JavaScript Arrays
<html>
<body>
The Array.splice() method adds array
<h2>JavaScript Arrays</h2> elements:

<p>The Array.splice() method adds array elements:</p> Banana,Orange,Lemon,Kiwi,Apple,Mango

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At position 2, add 2 elements:


fruits.splice(2, 0, "Lemon", "Kiwi");

document.getElementById("demo").innerHTML = fruits;
</script>

</body>
</html>

Java script Date objects


 The date object is used for obtaining date and time

Method Description

getTime() Returns the no of milliseconds


getDate() Returns the current date
getDay() Returns the current day

36 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


getHours() Returns the hour from 0 to 23

getMinute() Returns the minute value ranging from 0 to


59

setDate(value) Helps to set the desired date

setHour(hr,minute,second,ms) Set desired time

Example for Date Object Output


<html> Today's date: 27
<head> 0
</head>
<body>
2023
<script>
var date=new Date();
document.writeln("Today's date: "+date.getDate()+"<br>");
document.writeln(date.getDay()+"<br>");
document.writeln(date.getFullYear()+"<br>");
</script>
</script>
</body>
</html>
Boolean Object
• The Boolean object represents two values, either "true" or "false".
• var val = new Boolean(value);
Boolean Methods:
 toSource()-Returns a string containing the source of the Boolean object; you can use
this string to create an equivalent object.
 toString()-Returns a string of either "true" or "false" depending upon the value of the
object.
 valueOf()-Returns the primitive value of the Boolean object.
Example for Boolean Object Output
<html> flag.toString is : false
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type = "text/javascript">
var flag = new Boolean(false);
document.write( "flag.toString is : " + flag.toString() ); //
This method returns a string of either "true" or "false" depending
upon the value of the object.
</script>

37 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


</body>
</html>

Math Object

The JavaScript Math object allows you to perform mathematical tasks on


numbers.
Method Explanation
sqrt() It returns the square root of the given number
abs() It returns the absolute value of the given number.
floor() It returns largest integer value, lower than or equal to the given
number. Eg-> 5.3 will return 5
pow() It returns value of base to the power of exponent.
max() It returns maximum value of the given numbers.
min() It returns minimum value of the given numbers.
exp() It returns the exponential form of the given number.
sign() It returns the sign of the given number
sin() It returns the sine of the given number.
ceil() It returns a smallest integer value, greater than or equal to the given
number.

Example for Math Object Output


<!DOCTYPE html> 8
<html> 1
<body>

<script>
document.writeln(Math.ceil(7.2)+"<br>");
document.writeln(Math.ceil(0.2));
</script>

</body>
</html>

JAVA SCRIPT EVENT HANDLING

 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.

38 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


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 Event Handler Description


Performed

Keydown & onkeydown & When the user press and then release the key
Keyup 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

39 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


Window/Document events

Event Event Description


Performed Handler

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

Program Output
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is ACET");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's
this?"/>
</form>
</body>
</html>

MouseOver Event
Program Output
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--

40 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


function mouseoverevent()
{
alert("This is III CSE");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over
me</p>
</body>
</html>

Focus Event
Program Output
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background="
aqua";
}
//-->
</script>
</body>
</html>

Keydown Event
Program Output
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->

41 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


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

Load Event
Program Output
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

DHTML with JAVA SCRIPT

Introduction to DHTML
 DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
 Components of Dynamic HTML
o HTML 4.0
o CSS
o JavaScript
o DOM.
 HTML 4.0
o HTML is a client-side markup language, which is a core component of the
DHTML. It defines the structure of a web page with various defined basic
elements or tags.
 CSS
o CSS stands for Cascading Style Sheet, which allows the web users
or developers for controlling the style and layout of the HTML
elements on the web pages.

 JavaScript
o JavaScript is a scripting language which is done on a client-side.
o DHTML uses the JavaScript technology for accessing, controlling,
and manipulating the HTML elements.
 DOM
o DOM is the document object model. It is a w3c standard, which is a
standard interface of programming for HTML.
42 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
 Difference between HTML and DHTML

HTML DHTML
It is used for developing and It is used for creating and designing
creating web pages. the animated and interactive web
sites or pages.
This markup language creates This concept creates dynamic
static web pages. web pages.
A simple page which is created A page which is created by a
by a user without using the user using the HTML, CSS,
scripts or styles called as an DOM, and JavaScript
HTML page. technologies called a DHTML
page.
HTML is simply a markup DHTML is not a language, but it
language. is a set of technologies of web
development.
DHTML Tasks
Following are some of the tasks that can be performed with JavaScript:
• Performing html tasks
• Performing CSS tasks
• Handling events
• Validating inputs
Performing HTML Tasks:
DHTML Code performing HTML tasks Output
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p id = "geeks">Hello Geeks!</p>
<script style = "text/javascript">
document.getElementById("geeks").innerHTML ="A
computer science portal for geeks";
</script>
</body>
</html>
Performing CSS Tasks:
DHTML CSS for changing the style of the HTML element

DHTML Code performing HTML tasks Output

43 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following
different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>

DHTML Events
• An event is defined as changing the occurrence of an object.
• It is compulsory to add the events in the DHTML page. Without events, there will be
no dynamic content on the HTML page. The event is a term in the HTML, which
triggers the actions in the web browsers.
• Example of events:
• Click a button.
• Submitting a form.
• An image loading or a web page loading, etc.
DHTML Code performing HTML tasks Output
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi Akshaya!!!";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
44 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>

Validate input data using JavaScript.


Validate input data using JavaScript. Output
<style>
body {
margin-left: 50%;
}

h1 {
color: green;
}
</style>
<h1>
GeeksforGeeks
</h1>
<h4>
DHTML JavaScript
</h4>
<p>
Enter graduation percentage:
</p>
<input id="perc">
<button type="button" onclick="Validate()">
Submit
</button>
<p id="demo"></p>
<script>
function Validate() {
var x,text;
x=document.getElementById("perc").value;
if(isNaN(x)||x<60) {
window.alert("Not selected in GeeksforGeeks");
} else {

document.getElementById("demo").innerHTML=
"Selected: Welcome to GeeksforGeeks";

document.getElementById("demo").style.color="#009900";
}
}
45 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</script>

JSON Introduction

 JSON is a text-based data exchange format derived from JavaScript that is used in
web services and other connected applications.
 JSON defines only two data structures
Objects and Arrays
 An object is a set of name-value pairs
 Array is a list of values
 JSON defines seven value types: string, number, object, array, true, false and null.
 Objects are enclosed in braces ({})
 Array are enclosed in brackets ([])

JSON Syntax

JSON syntax is derived from JavaScript object notation syntax:

 Data is in name/value pairs


 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays

JSON Data - A Name and a Value


JSON data is written as name/value pairs (aka key/value pairs).
A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value: "name":"John"
JSON Objects
• JSON objects are written inside curly braces.
• Just like in JavaScript, objects can contain multiple name/value pairs:
• {"firstName":"John", "lastName":"Doe"}
JSON Arrays
• JSON arrays are written inside square brackets.
• Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
46 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
{"employees":[
{"name":"Ram", "email":"[email protected]", "age":23},
{"name":"Shyam", "email":"[email protected]", "age":28},
{"name":"John", "email":"[email protected]", "age":33},
{"name":"Bob", "email":"[email protected]", "age":41}
]}
Example for JSON Array:
<!DOCTYPE html>
<html>

<body>
<p id="para"></p>
<script>
var jsonObjectArray = {

// Assigned a JSON array of objects


// to the key "books"
"books": [
{
"name": "Let Us C",
"author": "Yashavant Kanetkar"
},
{
"name": "Rich Dad Poor Dad",
"author": "Robert Kiyosaki "
},

47 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


{
"name": "Introduction to Algorithms",
"author": "Cormen"
},
]
};

var x = jsonObjectArray.books[0];
document.getElementById("para").innerHTML= x.name + " by " + x.author;
</script>
</body>
</html>
Output:
Let Us C by Yashavant Kanetkar
JSON Function files:
Using JSON, it is possible to define a function in a separate external JS file and we
can access this functionality from HTML document.
Example code
myFile.js
student({
{“name”: “AAA”, “roll_no”: “10”, “city”: “Pune”},
{“name”: “BBB”, “roll_no”: “20”, “city”: “Mumbai”},
{“name”: “CCC”, “roll_no”: “30”, “city”: “Kolkata”},
{“name”: “DDD”, “roll_no”: “40”, “city”: “Chennai”},
JSON_File_Demo.html
<!DOCTYPE html>
<html>
<body>
<div id="myID"></div>
<script>

48 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE


function Student(arr){
var out="";
var i;
out+='<table border=1>'
out+='<tr><td>'+arr[i].roll_no+'</td><td>'+arr[i].name+'</td><td>'+arr[i].city+'</
td></tr>';
}
out+='</table>'
document.getElementById("myID").innerHTML=out;
}
</script>
<script src="myFile.js"></script>
</body>
</html>

Output
Roll_No Name City
10 AAA Pune
20 BBB Mumbai
30 CCC Kolkata
40 DDD Chennai

49 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE

You might also like