0% found this document useful (0 votes)
4 views45 pages

Unit 2

Uploaded by

iamvbenz1
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)
4 views45 pages

Unit 2

Uploaded by

iamvbenz1
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 – II

CLIENT-SIDE SCRIPTING AND HTML DOM

Introduction JavaScript in perspective-syntax-variables and data types-


Statements-Operators-Literals-Functions-Objects-Arrays-Built-in-Objects-
Javascript Debuggers. DOM-Introduction to the Document Object Model-
DOM History and levels -Intrinsic Event Handling-Modifying Element
Style-The Document Tree- DOM Event Handling.

INTRODUCTION TO JAVA SCRIPT

• JavaScript isa lightweight, cross-platform, single-


threaded, and interpreted compiled programming language.
• It is also known as the scripting language for webpages. It is well-known
for the development of web pages, and many non-browser environments
also use it.
• JavaScript contains a standard library of objects, such as Array, Date,
and Math, and a core set of language elements such as operators, control
structures, and statements.

• Client-side JavaScript extends the core language by supplying objects to


control a browser and its Document Object Model (DOM). For example,
client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page
navigation.
• Server-side JavaScript extends the core language by supplying objects
relevant to running JavaScript on a server. For example, server-side
extensions allow an application to communicate with a database, provide

UNIT-II Client-Side Scripting and HTML DOM


continuity of information from one invocation to another of the application,
or perform file manipulations on a server.

JavaScript can be added to HTML file in two ways:

• Internal JS: JavaScript can be directly added to our HTML file by writing
the code inside the <script> tag. The <script> tag can either be placed inside
the <head> or the <body> tag according to the requirement.
<script>
// JavaScript Code
</script>

• External JS: We can write JavaScript code in another files having an


[Link] and then link this file inside the <head> tag of the HTML file in
which we want to add this code.
<script src="[Link]"></script>
Features

• JavaScript was created in the first place for DOM manipulation. Earlier
websites were mostly static, after JS was created dynamic Web sites were
made.
• Functions in JS are objects. They may have properties and methods just like
other objects. They can be passed as arguments in other functions.
• Can handle date and time.
• Performs Form Validation although the forms are created using HTML.
• No compiler is needed.

Applications of JavaScript
• Web Development: Adding interactivity and behavior to static sites
JavaScript.
• Web Applications: With technology, browsers have improved to the extent
that a language was required to create robust web applications. When we

UNIT-II Client-Side Scripting and HTML DOM


explore a map in Google Maps then we only need to click and drag the
mouse.
• Server Applications: With the help of [Link], JavaScript made its way
from client to server and [Link] is the most powerful on the server side.
• Games: Not only in websites, but JavaScript also helps in creating games for
leisure.
• Smartwatches: JavaScript is being used in all possible devices and
applications. It provides a library PebbleJS which is used in smartwatch
applications.
• Art: Artists and designers can create whatever they want using JavaScript to
draw on HTML 5 canvas, and make the sound more effective also can be
used [Link] library.
• Machine Learning: This JavaScript [Link] library can be used in web
development by using machine learning.
• Mobile Applications: JavaScript can also be used to build an application for
non-web contexts.

Limitations of JavaScript

• Security risks: JavaScript can be used to fetch data using AJAX or by


manipulating tags that load data such as <img>, <object>, <script>. These
attacks are called cross-site script attacks.

• Performance: JavaScript does not provide the same level of performance as


offered by many traditional languages as a complex program written in
JavaScript would be comparatively slow.

• Complexity: To master a scripting language, programmers must have a


thorough knowledge of all the programming concepts, core language objects,
and client and server-side objects otherwise it would be difficult for them to
write advanced scripts using JavaScript.

• Weak error handling and type checking facilities: It is a weakly typed


language as there is no need to specify the data type of the variable.

UNIT-II Client-Side Scripting and HTML DOM


VARIABLES AND DATATYPES IN JAVASCRIPT

Variables and data types are foundational concepts in programming, serving


as the building blocks for storing and manipulating information within a
program.

Syntax

var Keyword

The var keyword is used to declare a variable. It has a function-scoped or


globally-scoped behaviour.

Sample Code

var x = 10;

[Link](x);

const Keyword

The const keyword declares variables that cannot be reassigned.

const PI = 3.14;

Data Types

• JavaScript is a dynamically typed (also called loosely typed) scripting


language.
• In JavaScript, variables can receive different data types over time.

Primitive Data Types

The predefined data types provided by JavaScript language are known as


primitive data types. Primitive data types are also known as in-built data types.

• Number: JavaScript numbers are always stored in double-precision 64-bit


binary format IEEE 754. Unlike other programming languages, you don’t
need int, float, etc to declare different numeric values.

UNIT-II Client-Side Scripting and HTML DOM


• String: JavaScript Strings are similar to sentences. They are made up of a
list of characters, which is essentially just an “array of characters, like “Hello
GeeksforGeeks” etc.
• Boolean: Represent a logical entity and can have two values: true or false.
• Null: This type has only one value that is null.
• Undefined: A variable that has not been assigned a value is undefined.
• Symbol: Symbols return unique identifiers that can be used to add unique
property keys to an object that won’t collide with keys of any other code that
might add to the object.
• BigInt: BigInt is a built-in object in JavaScript that provides a way to
represent whole numbers larger than 2^53-1.
Non-Primitive Data Types

• The data types that are derived from primitive data types of the JavaScript
language are known as non-primitive data types.

• It is also known as derived data types or reference data types.

Object: It is the most important data type and forms the building blocks for
modern JavaScript.

The key (name) must always be a string, but the value can be of any data
type. Let's see a simple example,

let name = {}; // It will create an empty object.

let emp = {
firstname : "Ram",
lastname : "Singh",
salary : 20000,
insured : true
};

2. Array in JavaScript

• An array is a collection of values or a list of values.


• The values can be of the same type or of different types.
• To create an array in JavaScript, you can use square brackets [] and inside
the square brackets, you can specify the comma-separated list of values.

UNIT-II Client-Side Scripting and HTML DOM


• Each element in the array gets a numeric position, known as its index.
The array index starts from 0, so that the first array element is arr[0] and
not arr[1].

Let's take an example of a JavaScript array:

// Creating an Array

var cars = ["Ferrari", "Volvo", "BMW", "Maseratt”]

JavaScript typeOf Operator

The typeOf operator in JavaScript can be used to check the data type of any
value.

Here are a few examples to see how this works:

let a = null;

[Link](typeOf a); // null

// Array datatype

let cars = ["Ferrari", "Volvo", "BMW", "Maseratti"];

[Link](typeOf cars)); // array

Global and Local variables in JavaScript

Global Variables

• Global variables in JavaScript are those declared outside of any function


or block scope.
• They are accessible from anywhere within the script, including inside
functions and blocks.
• Variables declared without the var, let, or const keywords inside a
function automatically become global variables.

Local Variables

• Local variables are defined within functions in JavaScript.


• They are confined to the scope of the function that defines them and
cannot be accessed from outside.
UNIT-II Client-Side Scripting and HTML DOM
• Attempting to access local variables outside their defining function results
in an error.

How to use variables

• The scope of a variable or function determines what code has access to it.
• Variables that are created inside a function are local variables, and local
variables can only be referred to by the code within the function.
• Variables created outside of functions are global variables, and the code in
all functions has access to all global variables.
• If you forget to code the var keyword in a variable declaration, the JavaScript
engine assumes that the variable is global. This can cause debugging
problems.
• In general, it’s better to pass local variables from one function to another as
parameters than it is to use global variables. That will make your code easier
to understand with less chance of errors.

Sample Code for Global Variable Declaration

let petName = 'Raguuu' // Global variable

myFunction()
function myFunction()
{
fruit = 'apple'; // Considered global

[Link](typeof petName +'- ' +'My pet name is ' + petName)


}
[Link]( typeof petName + '- ' + 'My pet name is ' + petName + 'Fruit
name is ' + fruit)

Sample Code for Local Variable Declaration


myfunction();
anotherFunc();
let petName;
function myfunction() {
let petName = "Sizzer"; // local variable
[Link](petName);

UNIT-II Client-Side Scripting and HTML DOM


}
function anotherFunc() {
let petName = "Tom"; // local variable
[Link](petName);
}
[Link](petName);
OPERATORS

• JavaScript operators are symbols that are used to perform operations on


operands.
• They are an essential part of the JavaScript language, allowing developers
to execute various types of operations such as arithmetic, assignment,
comparison, logical operations, and more.
Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations. The basic
arithmetic operators in JavaScript include:
• Addition (+): Adds two operands.
• Subtraction (-): Subtracts the second operand from the first.
• Multiplication (*): Multiplies two operands.
• Division (/): Divides the first operand by the second.
• Modulus (%): Returns the remainder of dividing the first operand by the
second.
• Increment (++): Increases an operand's value by one.
• Decrement (--): Decreases an operand's value by one.
Here's an example of arithmetic operators in action:
let a = 3;
let b = 2;
let sum = a + b; // 5
let difference = a - b; // 1
let product = a * b; // 6
let quotient = a / b; // 1.5
let remainder = a % b; // 1

Assignment Operators
• Assignment operators are used to assign values to variables.

UNIT-II Client-Side Scripting and HTML DOM


• The simple assignment operator is = , but there are also compound
assignment operators that combine arithmetic operations with assignment,
such as += , -= , *= , /= , and %= .
For example:
let x = 10;
x += 5; // x is now 15

Comparison Operators
Comparison operators compare two values and return a Boolean value
( true or false ). Some of the comparison operators include:
• Equal (==): Checks if the values of two operands are equal.
• Strict equal (===): Checks if the values and types of two operands are equal.
• Not equal (!=): Checks if the values of two operands are not equal.
• Strict not equal (!==): Checks if the values and types of two operands are not
equal.
• Greater than (>): Checks if the value of the left operand is greater than the
value of the right operand.
• Less than (<): Checks if the value of the left operand is less than the value of
the right operand.
Here's an example:
let num1 = 5;
let num2 = "5";
let num3 = 10;

[Link](num1 == num2); // true


[Link](num1 === num2); // false
[Link](num1 < num3); // true

Logical Operators
Logical operators are used to determine the logic between variables or values.
They include:
• Logical AND (&&): Returns true if both operands are true.
• Logical OR (||): Returns true if at least one of the operands is true.
• Logical NOT (!): Returns true if the operand is false.
Example:
let val1 = true;
let val2 = false;
UNIT-II Client-Side Scripting and HTML DOM
[Link](val1 && val2); // false
[Link](val1 || val2); // true
[Link](!val1); // false

Ternary Operator
The ternary operator is the only JavaScript operator that takes three operands. It
is often used as a shortcut for the if statement.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;

Example:
let age = 18;
let isAdult = (age >= 18) ? true : false;
[Link](isAdult); // true

JavaScript Literals and Keywords


• Literals in JavaScript means values.
• A JavaScript Literal can be a numeric, string, floating-point value, a
boolean value, an array, or an object.

JavaScript supports various types of literals which are listed below:

• Numeric Literal
• Floating-point Literal
• Boolean Literal
• String Literal
• Array Literal
• Regular Expression Literal
• Object Literal

Numeric Literal in JS

• It can be a decimal value(base 10), a hexadecimal value(base 16), or an


octal value(base 8).
• Decimal numeric literals consist of a sequence of digits (0-9) without a
leading 0(zero). These are integer values that you will be using mostly in
your JS code.

UNIT-II Client-Side Scripting and HTML DOM


• Hexadecimal numeric literals include digits(0-9), letters (a-f) or (A-F).
• Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric
literal indicates octal format.

Numeric Literals Example:

• Here is an example of the different types of numeric literals.

120 // decimal literal

021434 // octal literal

0x4567 // hexadecimal literal

Floating-Point Literal in JS

• It contains a decimal point, for example, the value 1.234


• A fractional value is a floating-point literal.
• It may contain an Exponent.

Floating-Point Literal Example:

Here is an example of floating point literals.

6.99689 // floating-point literal

-167.39894 // negative floating-point literal

Boolean Literal in JS

Boolean literal can have two values, either true or false.

true // Boolean literal

false // Boolean literal

String Literal in JS

A string literal is a combination of characters (alphabets or numbers or special


characters) enclosed within single('') or double quotation marks ("").

"Study" // String literal

'tonight' // String literal


UNIT-II Client-Side Scripting and HTML DOM
String literals can have some special characters too which are listed in the table
below.

Character Description

\b It represents a backspace.

\f It represents a Form Feed.

\n It represents a new line.

\r It represents a carriage return.

\t It represents a tab.

\v It represents a vertical tab.

\' It represents an apostrophe or a single quote.

\" It represents a double quote.

\\ It represents a backslash character.

It represents a Unicode character specified by a four-digit hexadecimal


\uXXXX
number.

Array Literal in JS

• An array literal is an array in JavaScript created using the square bracket


([]) with or without values.
• Whenever you create an array using an array literal, it is initialized with
the elements specified in the square bracket.

JavaScript Array Literal Example:

Example,

["Abhishek","Supriya","Joey"]; // Array literal

Even when you assign an array to a variable, if you create the array directly
using the square brackets, it is an array literal.

let students = ["Abhishek","Supriya","Joey"]; // Array literal

UNIT-II Client-Side Scripting and HTML DOM


In JavaScript, we can create an array using the Array object or using an array
literal.

Regular Expression Literal in JS

Regular Expression is a bunch of characters defining a pattern, that is used to


match a character or string in some text. It is created by enclosing the regular
expression string between forward slashes.

JavaScript Regular Expression Example:

Here is an example,

var myregexp = /ab+c/; // Regular Expression literal

var myregexp = new RegExp("abc"); // Regular Expression object

Object Literal in JS

It is a collection of key-value pairs enclosed in curly braces ({}). The key-value


pairs are separated using a comma.

JavaScript Object Literal Example:

Here is an example,

var games = {cricket :11, chess :2, carom: 4} // Object literal

In the code example above, on the right side of the equals to or assignment
operator, we have the object literal.

JavaScript Keywords

• Every programming language has its keywords or reserved words.


• Every keyword is created to perform a specific task or to be used for a
specific purpose, which is known to the compiler or the interpreter.

JavaScript supports a rich set of keywords, listed in the below table.

UNIT-II Client-Side Scripting and HTML DOM


Keyword Description

for The for keyword is used to create a for loop.

They do and while both keywords are used to create loops in


do/while
JavaScript.

if/else The if and else keywords are used to create conditional statements.

continue The continue keyword is used to resume the loop.

break It is used to break the loop.

function The function keyword is used to declare a function.

debugger It is used to call the debugger function

class The class keyword is used to declare the class.

return Return keyword is used to return function from the function.

export Used to export some functions, variables, etc. from a module

var, let, const The var, let and const keywords are used to declare a variable.

The switch creates various statement blocks and executes only on


switch
block depending on the condition or the case.

try/catch It is used to create a block for error handling of the statements.

JavaScript Arrays

• An array in JavaScript is a data structure used to store multiple values in


a single variable.
• It can hold various data types and allows for dynamic resizing.
• Elements are accessed by their index, starting from 0.

UNIT-II Client-Side Scripting and HTML DOM


Basic Terminologies of JavaScript Array
Array: A data structure in JavaScript that allows you to store multiple values in
a single variable.
Array Element: Each value within an array is called an element. Elements are
accessed by their index.
Array Index: A numeric representation that indicates the position of an element
in the array. JavaScript arrays are zero-indexed, meaning the first element is at
index 0.
Array Length: The number of elements in an array. It can be retrieved using
the length property.

Declaration of an Array
There are basically two ways to declare an array i.e. Array Literal and Array
Constructor.

1. Creating an Array using Array Literal


Creating an array using array literal involves using square brackets [] to define
and initialize the array. This method is concise and widely preferred for its
simplicity.

Syntax:

let arrayName = [value1, value2, ...];


Example:
// Creating an Empty Array
let names = [];
[Link](names);
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
[Link](courses);

Output
[]
[ 'HTML', 'CSS', 'Javascript', 'React' ]

UNIT-II Client-Side Scripting and HTML DOM


2. Creating an Array using Array Constructor (JavaScript new Keyword)
The “Array Constructor” refers to a method of creating arrays by invoking the
Array constructor function. This approach allows for dynamic initialization and
can be used to create arrays with a specified length or elements.

Syntax:

let arrayName = new Array();


Example:

// Declaration of an empty array


// using Array constructor
let names = new Array();
[Link](names);

// Creating and Initializing an array with values


let courses = new Array("HTML", "CSS", "Javascript", "React");
[Link](courses);

// Initializing Array while declaring


let arr = new Array(3);
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
[Link](arr);

Output
[]
[ 'HTML', 'CSS', 'Javascript', 'React' ]
[ 10, 20, 30 ]
Note: Both the above methods do exactly the same. Use the array literal method
for efficiency, readability, and speed.

Basic Operations on JavaScript Arrays


1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The index in
the arrays starts with 0.

UNIT-II Client-Side Scripting and HTML DOM


// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];

// Accessing Array Elements


[Link](courses[0]);
[Link](courses[1]);
[Link](courses[2]);
[Link](courses[3]);
Output
HTML
CSS
Javascript
React
2. Accessing the First Element of an Array
The array indexing starts from 0, so we can access first element of array using
the index number.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing First Array Elements


let firstItem = courses[0];

[Link]("First Item: ", firstItem);

Output
First Item: HTML
3. Accessing the Last Element of an Array
We can access the last array element using [[Link] – 1] index number.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing Last Array Elements


let lastItem = courses[[Link] - 1];

[Link]("First Item: ", lastItem);

UNIT-II Client-Side Scripting and HTML DOM


Output
First Item: React
4. Modifying the Array Elements
Elements in an array can be modified by assigning a new value to their
corresponding index.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
[Link](courses);

courses[1]= "Bootstrap";
[Link](courses);

Output
[ 'HTML', 'CSS', 'Javascript', 'React' ]
[ 'HTML', 'Bootstrap', 'Javascript', 'React' ]
5. Adding Elements to the Array
Elements can be added to the array using methods like push() and unshift().

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React"];

// Add Element to the end of Array


[Link]("[Link]");

// Add Element to the beginning


[Link]("Web Development");

[Link](courses);

Output
[ 'Web Development', 'HTML', 'CSS', 'Javascript', 'React', '[Link]' ]
6. Removing Elements from an Array
Remove elements using methods like pop(), shift(), or splice().
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];
[Link]("Original Array: " + courses);

UNIT-II Client-Side Scripting and HTML DOM


// Removes and returns the last element
let lastElement = [Link]();
[Link]("After Removing the last elements: " + courses);

// Removes and returns the first element


let firstElement = [Link]();
[Link]("After Removing the First elements: " + courses);

// Removes 2 elements starting from index 1


[Link](1, 2);
[Link]("After Removing 2 elements starting from index 1: " + courses);
Output

Original Array: HTML,CSS,Javascript,React,[Link]


After Removing the last elements: HTML,CSS,Javascript,React
After Removing the First elements: CSS,Javascript,React
After Removing 2 elements starting from index 1: CSS
7. Array Length
Get the length of an array using the length property.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];

let len = [Link];

[Link]("Array Length: " + len);

Output
Array Length: 5
8. Increase and Decrease the Array Length
We can increase and decrease the array length using the JavaScript length
property.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];

// Increase the array length to 7

UNIT-II Client-Side Scripting and HTML DOM


[Link] = 7;

[Link]("Array After Increase the Length: ", courses);

// Decrease the array length to 2


[Link] = 2;
[Link]("Array After Decrease the Length: ", courses)

Output
Array After Increase the Length: [ 'HTML', 'CSS', 'Javascript', 'React', '[Link]',
<2 empty items> ]
Array After Decrease the Length: [ 'HTML', 'CSS' ]
9. Iterating Through Array Elements
We can iterate array and access array elements using for and forEach loop.

Example: It is an example of for loop.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through for loop


for (let i = 0; i < [Link]; i++) {
[Link](courses[i])
}

Output
HTML
CSS
JavaScript
React
Example: It is the example of [Link]() loop.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Iterating through forEach loop


[Link](function myfunc(elements) {

UNIT-II Client-Side Scripting and HTML DOM


[Link](elements);
});
Output
HTML
CSS
JavaScript
React
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new array
containing joined arrays elements.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];
let otherCourses = ["[Link]", "[Link]"];

// Concatenate both arrays


let concateArray = [Link](otherCourses);

[Link]("Concatenated Array: ", concateArray);

Output
Concatenated Array: [ 'HTML', 'CSS', 'JavaScript', 'React', '[Link]', '[Link]'
]
11. Conversion of an Array to String
We have a builtin method toString() to converts an array to a string.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Convert array ot String


[Link]([Link]());

Output
HTML,CSS,JavaScript,React

UNIT-II Client-Side Scripting and HTML DOM


12. Check the Type of an Arrays
The JavaScript typeof operator is used ot check the type of an array. It returns
“object” for arrays.

// Creating an Array and Initializing with Values


let courses = ["HTML", "CSS", "JavaScript", "React"];

// Check type of array


[Link](typeof courses);

Output
Object

Difference Between JavaScript Arrays and Objects


• JavaScript arrays use indexes as numbers.
• objects use indexes as names.

When to use JavaScript Arrays and Objects?


• Arrays are used when we want element names to be numeric.
• Objects are used when we want element names to be strings.

Recognizing a JavaScript Array


• There are two methods by which we can recognize a JavaScript array:
• By using [Link]() method
• By using instanceof method
Below is an example showing both approaches:

const courses = ["HTML", "CSS", "Javascript"];


[Link]("Using [Link]() method: ", [Link](courses))
[Link]("Using instanceof method: ", courses instanceof Array)

Output
Using [Link]() method: true
Using instanceof method: true
Note: A common error is faced while writing the arrays:

UNIT-II Client-Side Scripting and HTML DOM


const numbers = [5]
// and
const numbers = new Array(5)

const numbers = [5]


[Link](numbers)
The above two statements are not the same.

Output: This statement creates an array with an element ” [5] “.

[5]

const numbers = new Array(5)


[Link](numbers)

Output
[ <5 empty items> ]

Built-in Objects

• Built-in objects are not related to any Window or DOM object model.
• These objects are used for simple data processing in the JavaScript.

1. Math Object
• Math object is a built-in static object.
• It is used for performing complex math operations.

Math Properties

Math Property Description


SQRT2 Returns square root of 2.
PI Returns Π value.
E\ Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
LOG2E Returns base 2 logarithm of E.
LOG10E Returns 10 logarithm of E.

UNIT-II Client-Side Scripting and HTML DOM


Math Methods

Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.

Example: Simple Program on Math Object Methods


<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">

var value = [Link](20);


[Link]("ABS Test Value : " + value +"<br>");

var value = [Link](-1);


[Link]("ACOS Test Value : " + value +"<br>");

var value = [Link](1);


[Link]("ASIN Test Value : " + value +"<br>");

var value = [Link](.5);


[Link]("ATAN Test Value : " + value +"<br>");
</script>
</body>
</html>

UNIT-II Client-Side Scripting and HTML DOM


Output

ABS Test Value : 20


ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061

Example: Simple Program on Math Object Properties


<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
[Link]("E Value is :" + value1 + "<br>");

var value2 = Math.LN2


[Link]("LN2 Value is :" + value2 + "<br>");

var value3 = Math.LN10


[Link]("LN10 Value is :" + value3 + "<br>");

var value4 = [Link]


[Link]("PI Value is :" + value4 + "<br>");
</script>
</body>
</html>

Output:

E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793

UNIT-II Client-Side Scripting and HTML DOM


2. Date Object
• Date is a data type.
• Date object manipulates date and time.
• Date() constructor takes no arguments.
• Date object allows you to get and set the year, month, day, hour, minute,
second and millisecond fields.

Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at
12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current
locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes()Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00
AM.

UNIT-II Client-Side Scripting and HTML DOM


setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a human-readable
string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.

Example : JavaScript Date() Methods Program

<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
[Link]("<b>Locale String:</b> " +
[Link]()+"<br>");
[Link]("<b>Hours:</b> " + [Link]()+"<br>");
[Link]("<b>Day:</b> " + [Link]()+"<br>");
[Link]("<b>Month:</b> " + [Link]()+"<br>");
[Link]("<b>FullYear:</b> " + [Link]()+"<br>");
[Link]("<b>Minutes:</b> " + [Link]()+"<br>");
</script>
</center>
</body>
</html>

Output:
date object

3. String Object
• String objects are used to work with text.
• It works with a series of characters.

UNIT-II Client-Side Scripting and HTML DOM


Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties

Properties Description
Length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created the object.

String Methods

Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specified
position.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separating the
string into the substrings.
toLowerCase() It returns the calling string value converted lower case.
toUpperCase() Returns the calling string value converted to uppercase.

Example : JavaScript String() Methods Program


<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = [Link]();

UNIT-II Client-Side Scripting and HTML DOM


[Link]("<b>Char At:</b> " + [Link](1)+"<br>");
[Link]("<b>CharCode At:</b> " + [Link](2)+"<br>");
[Link]("<b>Index of:</b> " + [Link]("ide")+"<br>");
[Link]("<b>Lower Case:</b> " +
[Link]()+"<br>");
[Link]("<b>Upper Case:</b> " +
[Link]()+"<br>");
</script>
<center>
</body>
</html>

JavaScript Debugging

• Sometimes a code may contain certain mistakes.


• Being a scripting language, JavaScript didn't show any error message in
a browser.
• But these mistakes can affect the output.
Approaches
o Using [Link]() method
o Using debugger keyword

Using [Link]() method


• The [Link]() method displays the result in the console of the
browser.
• If there is any mistake in the code, it generates the error message.
Example
1. <script>
2. x = 10;
3. y = 15;
4. z = x + y;
5. [Link](z);
6. [Link](a);//a is not intialized
7. </script>

UNIT-II Client-Side Scripting and HTML DOM


Using debugger keyword

In debugging, generally we set breakpoints to examine each line of code step by


step. There is no requirement to perform this task manually in JavaScript.
JavaScript provides debugger keyword to set the breakpoint through the code
itself. The debugger stops the execution of the program at the position it is
applied.
Now, we can start the flow of execution manually. If an exception occurs, the
execution will stop again on that particular line.
1. <script>
2. x = 10;
3. y = 15;
4. z = x + y;
5. debugger;
6. [Link](z);
7. [Link](a);
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


1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:
1. var arrayname=[value1,value2.....valueN];

Example:
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<[Link];i++){
4. [Link](emp[i] + "<br/>");
5. }
6. </script>

UNIT-II Client-Side Scripting and HTML DOM


Output
/* length – Length of an array*/
Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
1. var arrayname=new Array();
Here, new keyword is used to create instance of array.
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7. for (i=0;i<[Link];i++){
8. [Link](emp[i] + "<br>");
9. }
10. </script>

Output
Arun
Varun
John

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.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<[Link];i++){
4. [Link](emp[i] + "<br>");
5. }
6. </script>

UNIT-II Client-Side Scripting and HTML DOM


Output

Jai
Vijay
Smith

HTML DOM (Document Object Model)

• HTML DOM (Document Object Model) is a hierarchical representation


of HTML documents.

• It defines the structure and properties of elements on a webpage, enabling


JavaScript to dynamically access, manipulate, and update content, enhancing
interactivity and functionality.

What is DOM?

• DOM, or Document Object Model, is a programming interface that


represents structured documents like HTML and XML as a tree of objects.

• It defines how to access, manipulate, and modify document elements


using scripting languages like JavaScript.

Three different parts:

• Core DOM – standard model for all document types


• XML DOM – standard model for XML documents
• HTML DOM – standard model for HTML documents

HTML DOM
• HTML DOM is a standard object model and programming interface for
HTML documents.

• HTML DOM is a way to represent the webpage in a structured


hierarchical way so that it will become easier for programmers and users to glide
through the document.

UNIT-II Client-Side Scripting and HTML DOM


Why is DOM Required?

• HTML is used to structure the web pages and Javascript is used to add
behavior to our web pages.

• When an HTML file is loaded into the browser, the JavaScript can not
understand the HTML document directly. So it interprets and interacts with the
Document Object Model (DOM), which is created by the browser based on the
HTML document.

• DOM is basically the representation of the same HTML document but in


a tree-like structure composed of objects.

• JavaScript can not understand the tags(<h1>H</h1>) in HTML document


but can understand object h1 in DOM.

The Document Object Model (DOM) is essential in web development for


several reasons:
• Dynamic Web Pages:
• Interactivity:
• Content Updates:
• Cross-Browser Compatibility:
• Single-Page Applications (SPAs):

Properties of DOM

Representation of the DOM


• Window Object: Window Object is object of the browser which is always
at top of the hierarchy. It is like an API that is used to set and access all the
properties and methods of the browser. It is automatically created by the
browser.
• Document object: When an HTML document is loaded into a window, it
becomes a document object. The ‘document’ object has various properties that
refer to other objects which allow access to and modification of the content of
the web page. If there is a need to access any element in an HTML page, we
always start with accessing the ‘document’ object. Document object is property
of window object.

UNIT-II Client-Side Scripting and HTML DOM


• Form Object: It is represented by form tags.
• Link Object: It is represented by link tags.
• Anchor Object: It is represented by a href tags.
• Form Control Elements: Form can have many control elements such as
text fields, buttons, radio buttons, checkboxes, etc.
Levels of DOM

DOM consisted of multiple levels, each representing different aspect of the


document.

• Level 0: Provides a low-level set of interfaces.


• Level 1: DOM level 1 can be described in two parts: CORE and HTML.

o CORE provides low-level interfaces that can be used to represent any


structured document.
o HTML provides high-level interfaces that can be used to represent HTML
documents.

• Level 2: consists of six specifications:


CORE2, VIEWS, EVENTS, STYLE, TRAVERSAL, and RANGE.

o CORE2: extends the functionality of CORE specified by DOM level 1.


o VIEWS: views allow programs to dynamically access and manipulate the
content of the document.
o EVENTS: Events are scripts that are either executed by the browser when
the user reacts to the web page.
o STYLE: allows programs to dynamically access and manipulate the
content of style sheets.
o TRAVERSAL: This allows programs to dynamically traverse the
document.
o RANGE: This allows programs to dynamically identify a range of content
in the document.

• Level 3: consists of five different specifications: CORE3, LOAD and


SAVE, VALIDATION, EVENTS, and XPATH.

o CORE3: extends the functionality of CORE specified by DOM level 2.

UNIT-II Client-Side Scripting and HTML DOM


o LOAD and SAVE: This allows the program to dynamically load the
content of the XML document into the DOM document and save the DOM
Document into an XML document by serialization.
o VALIDATION: This allows the program to dynamically update the
content and structure of the document while ensuring the document remains
valid.
o EVENTS: extends the functionality of Events specified by DOM Level 2.
o XPATH: XPATH is a path language that can be used to access the DOM
tree.

JAVA SCRIPT EVENT HANDLING

• JavaScript Events are actions or occurrences that happen in the


browser. They can be triggered by various user interactions or by the
browser itself.

• Common events include mouse clicks, keyboard presses, page loads,


and form submissions.

• Event handlers are JavaScript functions that respond to these events,


allowing developers to create interactive web applications.

Intrinsic Events

• Intrinsic events are meant to increase interactivity with the users of a site.
• They may not be directly analysed by HTML but they rather have to be
parsed by a client based or server based script (JavaScript, PHP, ASP).
• These events may be applied to majority of the elements.

Syntax:

<HTML-element Event-Type = "Action to be performed">

Some examples of DOM events:

• Click − This event occurs when a user clicks on an HTML element.


• Load − This event occurs when an HTML element is loaded.

UNIT-II Client-Side Scripting and HTML DOM


• Change − This event occurs when the value of an HTML element is
changed.
• Submit − This event occurs when an HTML form is submitted.

Common JavaScript Events Table

Event Attribute Description

onclick Triggered when an element is clicked.

onmouseover Fired when the mouse pointer moves over an element.

onmouseout Occurs when the mouse pointer leaves an element.

onkeydown Fired when a key is pressed down.

onkeyup Fired when a key is released.

onchange Triggered when the value of an input element changes.

onload Occurs when a page has finished loading.

onsubmit Fired when a form is submitted.

onfocus Occurs when an element gets focus.

onblur Fired when an element loses focus.

JavaScript Events Examples

a. Display a message in the alert box when the button is clicked using
onClick() event.

<!doctype html>
<html>

<head>

UNIT-II Client-Side Scripting and HTML DOM


<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>

<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>
</html>

Output

When clicked, the button triggers the `hiThere()` JavaScript function, which
displays an alert box with the message “Hi there!”.

b. Change the color by pressing UP arrow key using onkeyup() event. This
code defines a JavaScript function `changeBackground()` that changes
the background color of an input box when the up arrow key is pressed.
RGB color values are incremented with each key press, cycling through
colors.

Program
<!doctype html>
<html>

<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=[Link]('bg');
[Link]='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;

UNIT-II Client-Side Scripting and HTML DOM


c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>

<body>
<h4>The input box will change color when UP arrow key is pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write
something" style="color:#fff">
</body>
</html>

2. JavaScript Event Handlers


JavaScript event handlers are functions that are executed in response to
specific events occurring in the browser.

They can be attached to HTML elements using event attributes


like onclick, onmouseover, etc., or added dynamically using
the addEventListener() method in JavaScript.

<!DOCTYPE html>
<html>
<head>
<title>Event Handler Example</title>
</head>
<body>

<button onclick="myFunction()">Click me</button>

<script>
// JavaScript function to handle the click event
function myFunction() {
alert("Button clicked!");
}
</script>
</body>
</html>

UNIT-II Client-Side Scripting and HTML DOM


Output

When the button is clicked, the `myFunction()` JavaScript function is invoked,


triggering an alert box displaying “Button clicked!”.
Modifying Element Style

The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style


• To change the style of an HTML element, use this syntax:
• [Link](id).[Link] = new style
• The following example changes the style of a <p> element:
Program

<html>
<body>
<p id="p2">HelloWorld!</p>
<script>
[Link]("p2").[Link] = "blue";
</script>
</body>
</html>
Using Events

➢ The HTML DOM allows you to execute code when an event occurs.

➢ Events are generated by the browser when "things happen" to HTML


elements:

• An element is clicked on
• The page has loaded
• Input fields are changed

This example changes the style of the HTML element with id="id1", when
the user clicks a button:

<!DOCTYPE html>
<html>
<body>
<h1 id="id1">MyHeading1</h1>
UNIT-II Client-Side Scripting and HTML DOM
<button type="button"
onclick="[Link]('id1').[Link]='red'">
ClickMe!</button>
</body>
</html>

DOM tree
• The backbone of an HTML document is tags.
• According to the Document Object Model (DOM), every HTML tag is an
object. Nested tags are “children” of the enclosing one. The text inside a
tag is an object as well.
• All these objects are accessible using JavaScript, and we can use them to
modify the page.
For example, [Link] is the object representing the <body> tag.
Program
[Link] = 'red'; // make the background red
setTimeout(() => [Link] = '', 3000); // return back
Output

will make the <body> red for 3 seconds

[Link] to change the background color of [Link],


but there are many other properties.

UNIT-II Client-Side Scripting and HTML DOM


• Every tree node is an object.
• Tags are element nodes (or just elements) and form the tree
structure: <html> is at the root, then <head> and <body> are its
children, etc.
• The text inside elements forms text nodes, labelled as #text. A text node
contains only a string. It may not have children and is always a leaf of the
tree.
No space-only text nodes

Autocorrection
➢ If the browser encounters malformed HTML, it automatically corrects it
when making the DOM.
➢ For instance, the top tag is always <html>.
➢ Even if it doesn’t exist in the document, it will exist in the DOM, because
the browser will create it. The same goes for <body>.

UNIT-II Client-Side Scripting and HTML DOM


DOM EVENT HANDLING

• Event handling in the DOM (Document Object Model) is the process of


detecting and responding to user interactions or system events on a web
page.
• Events can be triggered by a variety of actions, such as clicking a button,
submitting a form, scrolling the page, or resizing the window.
• Event handling allows web developers to create dynamic and interactive
user interfaces that respond to user input in real-time.
• In the DOM, events are represented as objects, and event handling is
implemented through event listeners.
Event Listeners
• Event listeners are the foundation of event handling in the DOM.
• An event listener is a function that waits for a specific event to occur on an
HTML element and executes a set of instructions when the event is
triggered.
• The event listener is attached to the HTML element using the
addEventListener() method, which takes two arguments: the name of the
event to listen for and the function to be executed when the event is
triggered.

Program
const button = [Link]('button');
[Link]('click', () => {
alert('Button clicked!');
});
Explanation:
• First select a button element using the querySelector() method.
• Then attach an event listener to the button using the addEventListener()
method.

UNIT-II Client-Side Scripting and HTML DOM


• The event we're listening for is 'click', and the function we want to execute
when the event occurs is an anonymous function that displays an alert
message.
Types of Events
There are many types of events that can be handled in the DOM, including:
Mouse events: click, dblclick, mouseover, mouseout, mousemove, mousedown,
mouseup.
Keyboard events: keydown, keyup, keypress.
Form events: submit, reset, change, focus, blur.
Window events: load, unload, resize, scroll.
Touch events: touchstart, touchend, touchmove.
[Link] Event:

Mouse events are some of the most commonly used events in web development.

Here's an example of how to handle a click event:

Program
const button = [Link]('button');
[Link]('click', () => {
alert('Button clicked!');
});

Output
Displaying an alert message when the button is clicked.

[Link] Events
Keyboard events are another important type of event in the DOM.

Here's an example of how to handle a keypress event:

[Link]('keypress', (event) => {


[Link](`You pressed the ${[Link]} key.`);
});

UNIT-II Client-Side Scripting and HTML DOM


Output
When a key is pressed, the event object is passed to the callback function, and we
display a message in the console that shows which key was pressed.
[Link] Events
Form events are used to handle interactions with HTML form elements.
Here's an example of how to handle a submit event on a form:

Program

const form = [Link]('form');


[Link]('submit', (event) => {
[Link]();
const input = [Link]('input');
[Link](`You entered: ${[Link]}`);
});

Output

When the form is submitted, we prevent the default behavior (which is to reload
the page), and display the value of the input field in the console.

[Link] Events

Window events are used to handle interactions with the browser window.
Here's an example of how to handle a resize event:

Program

[Link]('resize', () => {
[Link](`Window size changed to
${[Link]}x${[Link]}`);
});

Output

When the window is resized, we display the new width and height of the window
in the console.

UNIT-II Client-Side Scripting and HTML DOM


[Link] Events

Touch events are used to handle interactions with touchscreens on mobile


devices.

Here's an example of how to handle a touchstart event:

Program

const box = [Link]('.box');


[Link]('touchstart', (event) => {
[Link](`Touch started at
(${[Link][0].clientX},${[Link][0].clientY})`);
});

Output:
When the user touches the box, we display the coordinates of the touch in the
console.

UNIT-II Client-Side Scripting and HTML DOM

You might also like