0% found this document useful (0 votes)
4 views

Unit No.2 Client-Side Scripting

The document provides an overview of JavaScript objects, including their properties and methods, as well as how to create and manipulate them. It explains the concept of objects as collections of key/value pairs and details the use of constructors and literals for object creation. Additionally, it covers JavaScript's Date and String objects, along with their respective methods and properties.

Uploaded by

Vrushabh Taskar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit No.2 Client-Side Scripting

The document provides an overview of JavaScript objects, including their properties and methods, as well as how to create and manipulate them. It explains the concept of objects as collections of key/value pairs and details the use of constructors and literals for object creation. Additionally, it covers JavaScript's Date and String objects, along with their respective methods and properties.

Uploaded by

Vrushabh Taskar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 270

2 Client-Side Scripting

JavaScript Objects

 Objects are one of JavaScript's data types.


 Objects are used to store key/value
(name/value) collections.
 A JavaScript object is a collection of named
values.
 Real Life Objects
 In real life, objects are things like:
houses, cars, people, animals, or any
other subjects.
 Here is a car object example:
JavaScript Objects

Car Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()


JavaScript Objects

Object Properties

A real life car has properties like weight and color:

car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.

Car objects have the same properties, but the values differ from car to car.

Object Methods
A real life car has methods like start and stop:

car.start(), car.drive(), car.brake(), car.stop().

Car objects have the same methods, but the methods are performed at different times.
JavaScript Variables
JavaScript Objects
JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:


Example
let car = "Fiat";

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<h2>Creating a Variable</h2>
<p id="demo"></p>

<script>
// Create and a Variable:
let car = "Fiat";
document.getElementById("demo").innerHTML = "Car: " + car;
</script>

</body>
</html>
JavaScript Objects

Output:

JavaScript Variables
Creating a Variable
Car: Fiat
JavaScript Objects
JavaScript Objects

Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named
car:

Example
const car = {type:"Fiat", model:"500", color:"white"};
JavaScript Objects
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Creating an Object</h2>

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

<script>
// Create an Object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display Data from the Object:


document.getElementById("demo").innerHTML =
"The car type is " + car.type;
</script>

</body>
</html>
JavaScript Objects
Output:

JavaScript Objects

Creating an Object

The car type is Fiat


JavaScript Object Definition
How to Define a JavaScript Object

• Using an Object Literal


• Using the new Keyword
• Using an Object Constructor

1. JavaScript Object Literal

An object literal is a list of name:value pairs inside curly braces {}.


{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

Creating a JavaScript Object


These examples create a JavaScript object with 4 properties:
Examples
// Create an Object
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

Try it Yourself »
JavaScript Object Definition
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>

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

<script>
// Create an Object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display Data from the Object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>
JavaScript Object Definition
Output:
Creating JavaScript Objects

Using an Object Literal

John is 50 years old.


JavaScript Object Definition
Using the new Keyword

This example create a new JavaScript object using new Object(), and then adds 4 properties:

Example
// Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Try it Yourself »
JavaScript Object Definition
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using the new Keyword</h2>

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

<script>
// Create an Object
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

// Diplay Object Content


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>
JavaScript Object Definition

Output:

Creating JavaScript Objects

Using the new Keyword

John is 50 years old.


JavaScript Object Definition

Object Properties
The named values, in JavaScript objects, are called properties.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
JavaScript Object Definition
Accessing Object Properties
You can access object properties in two ways:

objectName.propertyName

objectName["propertyName"]

Examples
person.lastName;
.
JavaScript Object Definition
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<p>There are two ways to access a property: object.property or object["property"]</p>

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

<script>
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display lastName from the Object:


document.getElementById("demo").innerHTML =
"The last name is " + person.lastName;
</script>

</body>
</html>
JavaScript Object Definition

Output:

JavaScript Objects

There are two ways to access a property: object.property or object["property"]

The last name is Doe


JavaScript Object Definition

Examples

person["lastName"];
JavaScript Object Definition
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<p>There are two ways to access a property: object.property or object["property"]</p>

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

<script>
// Create an Object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display lastName from the Object:


document.getElementById("demo").innerHTML =
"The last name is " + person["lastName"];
</script>

</body>
</html>
JavaScript Object Definition

Output:

JavaScript Objects

There are two ways to access a property: object.property or object["property"]

The last name is Doe


JavaScript Object Definition

JavaScript Object Methods


Methods are actions that can be performed on objects.
Methods are function definitions stored as property values.

Property Property Value


firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
JavaScript Object Definition

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Try it Yourself »
JavaScript Object Definition
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Object Methods</h2>
<p>A method is a function definition stored as a property value.</p>

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

<script>
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
JavaScript Object Definition

Output:

JavaScript Objects

Object Methods

A method is a function definition stored as a property value.


John Doe

In the example above, this refers to the person object:

this.firstName means the firstName property of person.

this.lastName means the lastName property of person.


The Date object is a datatype built into the JavaScript language. Date objects
JavaScript - Date
are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object using either local time or
UTC (universal, or GMT) time.

Syntax
You can use any of the following syntaxes to create a Date object using the
Date() constructor −

new Date( ) new


Date(milliseconds) new
Date(datestring) new
Date(year,month,date[,hour,minute
,second,millisecond ])

Note − Parameters in the brackets are


Parameters JavaScript - Date
•No Argument − With no arguments, the Date() constructor creates a Date object set to
the current date and time.

•milliseconds − When one numeric argument is passed, it is taken as the internal


numeric representation of the date in milliseconds, as returned by the getTime()
method. For example, passing the argument 5000 creates a date that represents five
seconds past midnight on 1/1/70.

•datestring − When one string argument is passed, it is a string representation of a date


in the format accepted by the Date.parse() method.

•7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −
JavaScript - Date
•year − Integer value representing the year. For compatibility (in order to avoid the Y2K
problem), you should always specify the year in full; use 1998 rather than 98.

•month − Integer value representing the month, beginning with 0 for January to 11 for
December.’

•date − Integer value representing the day of the month.

•hour − Integer value representing the hour of the day (24-hour scale).

•minute − Integer value representing the minute segment of a time reading.

•second − Integer value representing the second segment of a time reading.

•millisecond − Integer value representing the millisecond segment of a time reading.


JavaScript - Date

JavaScript Date Methods

Here is a list of the methods used with Date and their


description.

Date Static Methods


These methods are invoked using the Date object −

Sr.N
Name & Description
o.
Date.parse()Parses a string representation of a date
1 and time and returns the internal millisecond
representation of that date.
Date.UTC()Returns the millisecond representation of the
2
specified UTC date and time.
JavaScript - Date
JavaScript - Date

Date Object Constructor

Following is the Date Object Constructor in JavaScript −

Sr.N
Name & Description
o.
1 Date()Returns today's date and time.
JavaScript - Date
Example: Creating JavaScript Date Object
In the example below, we create a new instance of the date object.
In the output, you can observe that it returns the current time.

<html>
<head>
<title> JavaScript - Date object </title>
</head>
<body>
<p id = "output"> </p>
<script>
const date = new Date();
document.getElementById("output").innerHTML
=
"Today's date is : " + date;
</script>
</body>
</html>

Output
If we execute the above program, it returns the current time.
JavaScript - Date
Example: Setting up custom date
In the example below, We have passed the custom date string as a parameter of the Date()
constructor to create a custom date.

The Date() constructor returns the standard date string, which you can see in the output.

<html>
<head>
<title> JavaScript - Date object </title>
</head>
<body>
<p id = "output"> </p>
<script>
const date = new Date("August 19, 2024 09:30:54");
document.getElementById("output").innerHTML =
"The custom date is : " + date;
</script>
</body>
</html>

Output
If we execute the above program, it returns the custom time as provided.
JavaScript - Strings
The String object in JavaScript lets you work with a series of characters; it wraps JavaScript's
string primitive data type with a number of helper methods.

As JavaScript automatically converts between string primitives and String objects, you can call
any of the helper methods of the String object on a string primitive.

The string is a sequence of characters containing 0 or more characters. For example, 'Hello' is a
string.

Syntax
JavaScript strings can be created as objects using the String() constructor or as primitives using
string literals.

Use the following syntax to create a String object −

var val = new String(value);

The String parameter, value is a series of characters that has been properly encoded.

We can create string primitives using string literals and the String() function as follows −
JavaScript - Strings

str1 = 'Hello World!'; // using single quote


str2 = "Hello World!"; // using double quote
str3 = 'Hello World'; // using back ticks
str4 = String('Hello World!'); // using String() function

JavaScript String Object Properties


Here is a list of the properties of String object and their description.

Sr.No. Property Description

Returns a reference to the String function


1 constructor
that created the object.

2 length Returns the length of the string.

The prototype property allows you to add


3 prototype
properties and methods to an object.
JavaScript - Strings

JavaScript String Object Methods


Here is a list of the methods available in String object along with their
description.

Static Methods
The static methods are invoked using the 'String' class itself.

Sr.No. Property Description


Converts the sequence of
1 fromCharCode() UTF-16 code units into the
string.
Creates a string from the
2 fromCodePoint() given sequence of ASCII
values.
JavaScript - Strings

Examples
Let's take understand the JavaScript String object and string primitives with the
help of some examples.

Example: Creating JavaScript String Objects


In the example below, we used the string() constructor with the 'new' keyword
to create a string object.
<html> JavaScript - Strings
<head>
<title> JavaScript - String Object </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
const str = new String("Hello World!");
output.innerHTML += "str == " + str + "<br>";
output.innerHTML += "typeof str == " + typeof str;
</script>
</body>
</html>

Output
str == Hello World!
typeof str == object

typeof is a JavaScript keyword that will return the type of a variable when you call it.
JavaScript - Strings

Accessing a string
You can access the string characters using its index. The string index starts
from 0.

Example
In the example below, we access the character from the 0th and 4th index of the
string.
JavaScript - Strings

<html>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
let str1 = new String("Welcome!");
let str2 = "Welcome!";
output.innerHTML += "0th character is - " + str1[0] + "<br>";
output.innerHTML += "4th character is - " + str2[4] + "<br>";
</script>
</body>
</html>

Output
0th character is - W
4th character is - o
JavaScript - Array

The JavaScript Array object lets you store multiple values in a single variable.
An array is used to store a sequential collection of multiple elements of same or
different data types. In JavaScript, arrays are dynamic, so you don’t need to
specify the length of the array while defining the array. The size of a JavaScript
array may decrease or increase after its creation.

Syntax
Use the following syntax to create an array object in JavaScript −

const arr = new Array(val1, val2, val3, ..., valN)

Parameters

•val1, val2, val3, ..., valN − It takes multiple values as an argument to


initialize an array with them.
Return value JavaScript - Array
It returns an array object.

Note − When you pass the single numeric argument to the Array() constructor,
it defines the array of argument length containing the undefined values. The
maximum length allowed for an array is 4,294,967,295.

You can add multiple comma separated elements inside square brackets to
create an array using the array literal −

const fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as
follows.

fruits[0] is the first element


fruits[1] is the second element
fruits[2] is the third element
JavaScript - Array

JavaScript Array Reference


In JavaScript, the Array object enables storing collection of multiple elements under a single
variable name. It provides various methods and properties to perform operations on an array.
Here, we have listed the properties and methods of the Array class.

JavaScript Array Properties


Here is a list of the properties of the Array object along with their description −

Sr.N
Name & Description
o.
constructor
1 Returns a reference to the array function that created
the object.
length
2
Reflects the number of elements in an array.
The constructor method is a special method of a class for creating and initializing an object
instance of that class.
JavaScript - Array

JavaScript Array Methods


Here is a list of the methods of the Array object along with their
description −
Array Static methods
These methods are invoked using the Array class itself −

Sr.N
Name & Description
o.
from()
1
Creates a shallow copy of the array.
isArray()
2 Returns boolean values based on the argument is an
array.
Of()
3
Creates an array from multiple arguments.
JavaScript - Array

Basic Examples of JavaScript Array Object


In the following examples, we have demonstrated the
usage of basic methods and properties of JavaScript
Array Object −

Example (Creating JavaScript Array Object)


In the example below, the array ‘strs’ is initialized
with the string values passed as an Array()
constructor’s argument.

The ‘cars’ array contains 20 undefined elements. If


you pass multiple numeric values, it defines the array
containing those elements but needs to be careful
with a single numeric argument to the array()
<html>
<head> JavaScript - Array
<title> JavaScript - Array() constructor </title>
</head>
<body>
<p id = "demo"> </p>
<script>
const output = document.getElementById("demo");

let strs = new Array("Hello", "World!", "Tutorials Point");


output.innerHTML += "strs ==> " + strs + "<br>";

let cars = new Array(20);


output.innerHTML += "cars ==> " + cars + "<br>";
</script>
</body>
</html>

Output
Execute the above program to see the desired output.

strs ==> Hello,World!,Tutorials Point


cars ==> ,,,,,,,,,,,,,,,,,,,
JavaScript - Array
Example (Creating Arrays Using Array Literal)
In the example below, we have created different arrays. The arr1 array contains the
numbers, the arr2 array contains the strings, and the arr3 array contains the boolean
values.

<html>
<head>
<title> JavaScript - Array literals </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");

const arr1 = [10, 40, 50, 60, 80, 90]; // Array of numbers
const arr2 = ["Hello", "Hi", "How", "are", "you?"]; // Array of strings
const arr3 = [true, false, true, true]; // Array of booleans

output.innerHTML += "arr1 ==> " + arr1 + "<br>";


output.innerHTML += "arr2 ==> " + arr2 + "<br>";
output.innerHTML += "arr3 ==> " + arr3 + "<br>";
</script>
</body>
</html>
JavaScript - Array

Output
Execute the above program to see the desired output.

arr1 ==> 10,40,50,60,80,90


arr2 ==> Hello,Hi,How,are,you?
arr3 ==> true,false,true,true
JavaScript - Array

Accessing JavaScript Array Elements


The array index starts from 0. So, you can access the array element using its index.

let number = arr[index]


In the above syntax, ‘arr’ is an array, and ‘index’ is a number from where we need to
access the array element.

Example
In the example below, we have created the array of numbers and accessed the
elements from the 0th and 2nd index of the array. The element at the 0th index is 1,
and the element at the 2nd index is 6.
JavaScript - Array

<html>
<head>
<title> JavaScript - Accessing array elements </title>
</head>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 5, 6, 8, 90];
document.getElementById("output").innerHTML =
"Element at 0th index is : " + nums[0] + "<br>" +
"Element at 2nd index is : " + nums[2];
</script>
</body>
</html>

Output
Element at 0th index is : 1
Element at 2nd index is : 6
JavaScript Array length JavaScript - Array
The ‘length’ property of the array is used to find the length of the array.
let len = arr.length;

Example
In the example below, the ‘length’ property returns 5, as array contains 5 elements.

<html>
<head>
<title> JavaScript - Array length </title>
</head>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 5, 6, 8, 90];
document.getElementById("output").innerHTML =
"Array length is : " + nums.length;
</script>
</body>
</html>

Output
Array length is : 5
JavaScript - Array
Adding a new element to the array
You can use the push() method to insert the element at the end of the array. Another
solution is that you can insert the array at the index equal to the array length.

arr.push(ele)
OR
arr[arr.length] = ele;

In the above syntax, ‘ele’ is a new element to insert into the array. Here, if the array
length is N, the array contains elements from 0 to N – 1 index. So, we can insert the
new element at the Nth index.
JavaScript - Array
Example
In the example below, we insert 6 to the array using the push() method. Also, we used
the ‘length’ property to insert the element at the end.

<html>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
const nums = [1, 2, 3, 4, 5];
nums.push(6); // Inserting 6 at the end
output.innerHTML += "Updated array is : " + nums + "<br>";
nums[nums.length] = 7; // Inserting 7
output.innerHTML += "Updated array is : " + nums + "<br>"
</script>
</body>
</html>

Output
As we can see in the output, provided element has been added.

Updated array is : 1,2,3,4,5,6


Updated array is : 1,2,3,4,5,6,7
JavaScript - Array

Updating JavaScript Array Elements


To update any array element, you can access the array index and change its value.

arr[index] = ele;.

In the above syntax, ‘index’ is an index where we need to update a value with the ‘ele’
value.
JavaScript - Array
Example
In the example below, we update the element at the first index in the array.

<html>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 2, 3, 4, 5];
nums[0] = 100; // Updating first element
document.getElementById("output").innerHTML =
"Updated array is : " + nums;
</script>
</body>
</html>

Output
Updated array is : 100,2,3,4,5
JavaScript - Array
Traversing a JavaScript Array
You can use the loop to traverse through each array element. However, some built-in
methods exist to traverse the array, which we will see in later chapters.

for (let p = 0; p < nums.length; p++) {


// Access array using the nums[p]
}

Example
In the below code, the array contains 5 numbers. We used the for loop to traverse the array and
print each element.

However, while and do-while loops can also be used to traverse the array.
JavaScript - Array

<html>
<body>
<p id = "demo"> </p>
<script>
const output = document.getElementById("demo");
const nums = [1, 2, 3, 4, 5];
for (let p = 0; p < nums.length; p++) {
output.innerHTML += "nums[" + p + "] ==> " + nums[p] + "<br>";
}
</script>
</body>
</html>

Output
nums[0] ==> 1
nums[1] ==> 2
nums[2] ==> 3
nums[3] ==> 4
nums[4] ==> 5
JavaScript - Math

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

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

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

var pi_val = Math.PI; // Property

var sine_val = Math.sin(30); // Method

Let’s learn more about the Math object’s properties and method via the examples below.
JavaScript - Math
JavaScript Math Properties
Following is the list of properties of Math class in JavaScript −

Sr.No. Name & Description

E
1
Euler's constant and the base of natural logarithms, approximately 2.718.
LN2
2
Natural logarithm of 2, approximately 0.693.
LN10
3
Natural logarithm of 10, approximately 2.302.
LOG2E
4
Base 2 logarithm of E, approximately 1.442.
LOG10E
5
Base 10 logarithm of E, approximately 0.434.
PI
6
The ratio of a circle's circumference to its diameter is approximately 3.14159.
SQRT1_2
7
The square root of 1/2, equivalently, 1 over the square root of 2, is approximately 0.707.
SQRT2
8
The square root of 2, approximately 1.414.
JavaScript - Math
JavaScript Math Methods
JavaScript - Math
Example (Math object Properties)
The example below demonstrates that each property of the Math object has a constant value.

Here, we have accessed the values of the ‘E’, ‘LN2’, and ‘PI’ properties.

<html>
<head>
<title> JavaScript - Math object's properties </title>
</head>
<body>
<p id = "output"> </p>
<script>
document.getElementById("output").innerHTML =
"Math.E == " + Math.E + "<br>" +
"Math.LN2 == " + Math.LN2 + "<br>" +
"Math.LN10 == " + Math.LN10 + "<br>" +
"Math.PI == " + Math.PI + "<br>"+
"Math.LOG2E == " + Math.LOG2E + "<br>" +
"Math.LOG10E == " + Math.LOG10E;
</script>
</body>
</html>
JavaScript - Math

Output
After executing the above program, it returns the values of the provided Math properties.

Math.E == 2.718281828459045
Math.LN2 == 0.6931471805599453
Math.LN10 == 2.302585092994046
Math.PI == 3.141592653589793
Math.LOG2E == 1.4426950408889634
Math.LOG10E == 0.4342944819032518
JavaScript - Math
Example (Math ceil() method)
Here, we are computing the JavaScript ceil() method to return the smallest larger integer value than
the number passed as an argument. Here, the method returns 6 for the 5.9 value.

<html>
<head>
<title> JavaScript - Math.ceil() method </title>
</head>
<body>
<p id = "output"> </p>
<script>
let ans = Math.ceil(5.9);
document.getElementById("output").innerHTML =
"Math.ceil(5.9) = " + ans;
</script>
</body>
</html>

Output
After executing the above program, it returns the result as 6.

Math.ceil(5.9) = 6
JavaScript - Math
Example (Math max() method)
The Math.max() method is used to get the maximum value among the arguments passed as an array.

Here, we have passed six arguments to the Math.max() object, and the method returns the maximum
value from them.
<html>
<head>
<title> JavaScript - Math.max() method </title>
</head>
<body>
<p id = "output"> </p>
<script>
let ans = Math.max(100, 10, -5, 89, 201, 300);
document.getElementById("output").innerHTML =
"Math.max(100, 10, -5, 89, 201, 300) = " + ans + "<br>";
</script>
</body>
</html>

Output
After executing the above program, it returns 300 as maximum value.
JavaScript - The Number Object

The JavaScript Number object represents numerical data as floating-point numbers. It contains
different properties (constants) and methods for working on numbers. In general, you do not
need to worry about Number objects because the browser automatically converts number literals
to instances of the number class.

A JavaScript Number object can be defined using the Number constructor. Other types of data
such as strings, etc., can be converted to numbers using Number() function.

A JavaScript number is always stored as a floating-point value (decimal number). JavaScript


does not make a distinction between integer values and floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

Syntax
The syntax for creating a number object is as follows −

const val = new Number(number);


JavaScript - The Number Object

We can also create the number primitives by assigning the numeric values to the variables −

let num1 = 24;


let num2 = 35.65;

The JavaScript automatically converts the number primitive to the Number objects. So we
can use all properties and methods of Number object on number primitives.
JavaScript - The Number Object
Number Properties
Here is a list of each property and their description.

Sr.No. Property & Description

EPSILON
1 It represents the difference between 1 and the smallest floating
point number greater than 1.

MAX_SAFE_INTEGER
2
It returns the maximum safe integer value.

MAX_VALUE
3 The largest possible value a number in JavaScript can have
1.7976931348623157E+308.

MIN_SAFE_INTEGER
4
It returns the minimum safe integer value.

MIN_VALUE
5 The smallest possible value a number in JavaScript can have 5E-
324.
JavaScript - The Number Object

NaN
6
Equal to a value that is not a number.

NEGATIVE_INFINITY
7
A value that is less than MIN_VALUE.
POSITIVE_INFINITY
8 A value that is greater than
MAX_VALUE
prototype
A static property of the Number
object. Use the prototype property to
9
assign new properties and methods to
the Number object in the current
document.
constructor
Returns the function that created this
10
object's instance. By default this is the
Number object.
JavaScript - The Number Object
Number Methods
The Number object contains only the default methods (instance and static
methods) that are a part of every object's definition.

Instance Methods
Sr.No. Method & Description

toExponential()
1 Forces a number to display in exponential notation, even if
the number is in the range of standard notation.

toFixed()
2 Formats a number with a specific number of digits to the
right of the decimal.

toLocaleString()
3 Returns a string value version of the current number in a
format that may vary according to local settings.

toPrecision()
4 Defines how many total digits (including digits to the left
and right of the decimal) to display of a number.

toString()
5
Returns the string representation of the number's value.

valueOf()
6
Returns the number's value.
JavaScript - The Number Object
Static Methods

Sr.No. Method & Description

isNaN()
1
It checks whether the value is a valid number or not.

isFinite()
2
It checks whether the number is finite.

isInteger()
3
Returns Boolean when the number is an integer value.

isSafeInteger()
4
It ensures that the integer is a safe integer.

parseFloat()
5
Parses the float value from the string.

parseInt()
6
Parses the integer value from the string.
JavaScript - The Number Object

Examples
Let's take a few examples to demonstrate the properties and methods of Number.

Example: Creating Number Object


In the example below, the num variable contains the number object having the value 20. In the
output, you can see that type of the num variable is an object.

<html>
<body>
<p id = "output"> </p>
<script>
const num = new Number(20);
document.getElementById("output").innerHTML =
"num = " + num + "<br>" +
"typeof num : " + typeof num;
</script>
</body>
</html>
JavaScript - The Number Object

Output
num = 20
typeof num : object
JavaScript - The Number Object
Example: Number Methods
In the example below, we have used some properties of Number. You can try edit the
program to use more methods.

<html>
<body>
<div id="output"></div>
<script>
const num = 877.5312
document.getElementById("output").innerHTML =
"num.toExponetial() is : " + num.toExponential()+ "<br>"
+"num.toFixed() is : " + num.toFixed() + "<br>"
+"num.toPrecision(2) is : " + num.toPrecision(2) + "<br>";
</script>
</body>
</html>

Output
num.toExponetial() is : 8.775312e+2
num.toFixed() is : 878
num.toPrecision(2) is : 8.8e+2
JavaScript - The Number Object
JavaScript Number() Function
The Number() function converts the variable into a number. You can use it to change the data
type of the variable.

let num = Number(val)

Here val is a variable or value to convert into a number. It doesn't create a number object
instead it returns a primitive value.

Example
We passed the integer and string value to the Number() function in the example below. In the
output, the code prints the numeric values. The type of the num2 variable is a number, as the
Number() function returns the primitive number value.
JavaScript - The Number Object

<html>
<body>
<p id = "output"> </p>
<script>
let num = Number(10);
document.getElementById("output").innerHTML =
"num = " + num + "<br>" +
"typeof num = " + typeof num;
</script>
</body>
</html>

Output
num = 10
typeof num = number
JavaScript - The Boolean Object

The JavaScript Boolean object represents two values, either "true" or "false". You can create a
boolean object using the Boolean() constructor with a 'new' keyword. It takes a value as
parameter and returns a boolean object. If value parameter is omitted or is 0, -0, null, false,
NaN, undefined, or the empty string (""), the object has an initial value of false. In programming,
the if-else statement evaluates either the code of the 'if' block or the 'else' block based on the
boolean value of the conditional expression.

Syntax
Use the following syntax to create a boolean object.

const val = new Boolean(value);

Here value is an expression to convert into a Boolean object.

It returns an object containing the boolean value.

You can create a boolean primitive in JavaScript by assigning a boolean value to a variable −
let bool = true;
JavaScript - The Boolean Object
Boolean Properties
Here is a list of the properties of Boolean object −

Sr.No. Property & Description


constructorReturns a
reference to the Boolean
1
function that created the
object.
prototypeThe prototype
property allows you to add
2
properties and methods to an
object.
JavaScript - The Boolean Object
Boolean Methods
Here is a list of the methods of Boolean object and their description.

Sr.No. Method & Description


toSource()Returns a string containing
the source of the Boolean object; you can
1
use this string to create an equivalent
object.
toString()Returns a string of either
2 "true" or "false" depending upon the
value of the object.
valueOf()Returns the primitive value of
3
the Boolean object.
JavaScript - The Boolean Object

Example: Creating a Boolean Object


In the example below, we have defined the boolObj variable and stored the boolean object.

We used the typeof operator to check the type boolObj variable. In the output, you can observe
that the type of the boolObj is the object.

<html>
<body>
<p id = "output"> </p>
<script>
const boolObj = new Boolean('true'); //defining boolean object
document.getElementById("output").innerHTML = "typof boolObj == " + typeof boolObj;
</script>
</body>
</html>

Output
typof boolObj == object
JavaScript - The Boolean Object

JavaScript Boolean() Function


The Boolean() function allows the developer to get the boolean value after evaluating the
particular expression passed as a parameter.

Boolean(Expression);

Here value is an expression to evaluate and get related boolean values. The Boolean() function
returns the true or false based on the expression passed as a parameter.

Example
In the example below, We used the Boolean() function and passed different expressions as a
parameter. In the output, you can observe the boolean value returned by the Boolean() function.
JavaScript - The Boolean Object

<html>
<body>
<p id = "output"> </p>
<script>
let res = Boolean(100 > 90);
document.getElementById("output").innerHTML = "Boolean(100 > 90) : " + res + "<br>";
res = Boolean(100 < 90);
document.getElementById("output").innerHTML = "Boolean(100 < 90) : " + res + "<br>";
res = 100 == 90;
document.getElementById("output").innerHTML = "100 == 90 : " + res + "<br>";
</script>
</body>
</html>

Output
Boolean(100 > 90) : true
Boolean(100 < 90) : false
100 == 90 : false
JavaScript -Introduction to Events

What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a window,
etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users, data to be validated, and virtually any other
type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element
contains a set of events which can trigger JavaScript Code.
JavaScript -Introduction to Events

JavaScript Event Handlers


Event handler can be used as an attribute of the HTML element. It takes the inline JavaScript or
function execution code as a value.

Whenever any event triggers, it invokes the inline JavaScript code or executes the callback
function to perform the particular action.

In simple terms, it is used to handle the events.

Syntax
Users can follow the syntax below to use event handlers with HTML elements.

<div eventHandler = "JavaScript_code"> </div>


JavaScript -Introduction to Events

In the above syntax, you need to replace the 'eventHandler' with the actual event handler like
'onclick', 'onmouseover', etc. The 'JavaScript_code' should execute the function or run JavaScript
inline.

Example: Inline JavaScript with Event Handlers


In the code below, we have created the <button> element. Also, we have used the 'onclick' event
handler to capture the click event on the button.

We have written the inline JavaScript code to handle the event. In the inline JavaScript code, the
'this' keyword represents the <button> element, and we change the button's text color to red.

<html>
<body>
<h2> Click the button to Change its text's color </h2>
<button onclick = "this.style.color='red'"> Click Me </button>
<div id = "output"> </div>
</body>
</html>
JavaScript -Introduction to Events
Example: Function with Event Handlers

In the code below, we have created the <div> element and given style into the <head> section.

We used the 'onclick' event handler with the <button> element, which calls the handleClick()
function when the user clicks the button.

The handleClick() function takes the 'event' object as a parameter. In the handleClick() function,
we change the background color of the <div> element using JavaScript.
JavaScript -Introduction to Events
<html>
<head>
<style>
#test {
width: 600px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id = "test"> </div> <br>
<button onclick = "handleClick()"> Change Div Color </button>
<script>
function handleClick(event) {
var div = document.getElementById("test");
div.style.backgroundColor = "blue";
}
</script>
</body>
</html>
JavaScript -Introduction to Events
JavaScript -Introduction to Events
JavaScript -Introduction to Events

Example: Multiple Functions with Event Handlers

In the code below, we have added the 'ommouseenter' event handler with the <div> element. We
call the changeFontSize() and changeColor() functions when a user enters the mouse cursor in the
<div> element.

The changeFontSize() function changes the size of the text, and changeColor() function changes
the color of the text.

This way, you can invoke the multiple functions on the particular event.
JavaScript -Introduction to Events

<html>
<head>
<style>
#test {
font-size: 15px;
}
</style>
</head>
<body>
<h2> Hover over the below text to customize the font. </h2>
<div id = "test" onmouseenter = "changeFontSize(); changeColor();"> Hello World! </div>
<br>
<script>
function changeFontSize(event) {
document.getElementById("test").style.fontSize = "25px";
}
function changeColor(event) {
document.getElementById("test").style.color = "red";
}
</script>
</body>
JavaScript -Introduction to Events

Output:

Hover over the below text to customize the font.


Hello World!
JavaScript -Introduction to Events

JavaScript Event Object

The function that handles the event takes the 'event' object as a parameter. The 'event' object
contains the information about the event and the element on which it occurred.
There are various properties and methods are also available which can be used with the event
object to get information.

Object Description
It is a parent of all
Event
event objects.
JavaScript -Introduction to Events
Here is the list of different types of event objects. Each event object contains various events, methods, and
properties.

Object/Type Handles
It handles the CSS
AnimationEvent
animations.
It handles the changes of
ClipboardEvent
the clipboard.
It handles the drag-and-
DragEvent
drop events.
FocusEvent To handle the focus events.
It handles the changes in
HashChangeEvent the anchor part of the
URL.
InputEvent To handle the form inputs.
To handle the keyboard
KeyboardEvent
interaction by users.
It handles the media-
MediaEvent
related events.
To handle the mouse
MouseEvent
interaction by users.
JavaScript -Introduction to Events

To handle the navigation


PageTransitionEvent
between web pages.
It handles the changes in the
PopStateEvent
page history.
To handle the progress of the
ProgressEvent
file loading.
To handle changes in the web
StorageEvent
storage.
To handle touch interaction on
TouchEvent
the device’s screen.
TransitionEvent To handle CSS transition.
To handle the user interface
UiEvent
interaction by users.
To handle the mouse-wheel
WheelEvent
interaction by users.
JavaScript - DOM Events
The DOM events are actions that can be performed on HTML elements. When an event occurs,
it triggers a JavaScript function. This function can then be used to change the HTML element or
perform other actions.

Here are 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.

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

• Submit − This event occurs when an HTML form is submitted.

You can use the event handlers or addEventListener() method to listen to and react to the DOM
events. The addEventListener() method takes two arguments: the name of the event and the
function that you want to be called when the event occurs.

The DOM events are also referred as Document Object Model events. It is used to interact with
the DOM elements and manipulate the DOM elements from JavaScript when any event occurs.
JavaScript - DOM Events
The onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.

<html>
<head>
<script>
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
JavaScript - DOM Events
JavaScript - DOM Events
JavaScript - DOM Events
The ondblclick Event Type
We use the 'ondblclick' event handler in the code below with the element. When users double
click the button, it calls the changeColor() function.

In the changeColor() function, we change the color of the text. So, the code will change the text's
color when the user double-clicks the button.

Example

<html>
<body>
<h2 id = "text"> Hi Users! </h2>
<button ondblclick="changeColor()"> Double click me! </button>
<script>
function changeColor() {
document.getElementById("text").style.color = "red";
}
</script>
</body>
</html>
JavaScript - DOM Events
JavaScript - DOM Events
JavaScript - DOM Events
The onkeydown Event Type
We used the 'keydown' event in the code below with the <input> element. Whenever the user
will press any key, it will call the customizeInput() function.

In the customizeInput() function, we change the background color of the input and the input text to
red.

Example
<html>
<body>
<p> Enter charater/s by pressing any key </p>
<input type = "text" onkeydown = "customizeInput()">
<script>
function customizeInput() {
var ele = document.getElementsByTagName("INPUT")[0];
ele.style.backgroundColor = "yellow";
ele.style.color = "red";
}
</script>
</body>
<html>
JavaScript - DOM Events
JavaScript - DOM Events
JavaScript - DOM Events
The onmouseenter and onmouseleave Events
In the code below, we use the 'onmouseenter' and 'onmouseleave' event handlers to add a
hover effect on the <div> element.

When the mouse pointer enters the <div> element, it calls the changeRed() function to change
the text color to red, and when the mouse pointer leaves the <div> element, it calls the
changeBlack() function to change the text color to black again.

Example
<html>
<body>
<div id = "text" style = "font-size: 20px;" onmouseenter = "changeRed()" onmouseleave =
"changeBlack()"> Hover over the text. </div>
<script>
function changeRed() {
document.getElementById("text").style.color = "red";
}
function changeBlack() {
document.getElementById("text").style.color = "black";
}
</script>
</body>
</html>
JavaScript - DOM Events
JavaScript - DOM Events
JavaScript - Mouse Events
JavaScript mouse events allow users to control and interact with web pages using their mouse.
These events trigger specific functions or actions in response to user clicks, scrolls, drags, and
other mouse movements.

To handle mouse events in JavaScript, you can use the addEventListener() method. The
addEventListener() method takes two arguments: the event type and the event handler function.
The event type is the name of the event that you want to handle, and the event handler function
is the function that will be called when the event occurs.

In web development, JavaScript provides a powerful mechanism to respond to user interactions


with the mouse through a set of events. These events enable developers to create dynamic and
interactive web applications by capturing and handling various mouse-related actions.
JavaScript - Mouse Events
Common Mouse Events
Following are the most common JavaScript mouse events:

Mouse Event Description


When an element experiences the press of a mouse button, it
Click
triggers the click event.
The dblclick event fires upon the rapid double-clicking of a
Double Click
mouse button.
The initiation of a mouse click triggers the 'mousedown' event,
Mouse Down and Mouse Up while the completion of that click causes the 'mouseup' event to
occur.
When the mouse pointer moves over an element, it triggers the
'mousemove' event; this event supplies developers with
Mouse Move positional information about the mouse. This data empowers
them to devise responsive interfaces that are rooted in
dynamic mouse movements.
When the user attempts to open the context menu, typically by
right-clicking, they trigger the contextmenu event. This event
Context Menu
allows developers to customize or inhibit default behaviour of
the context menu.
JavaScript - Mouse Events
Common Mouse Events

When the mouse wheel rotates, it fires the 'wheel


Wheel event'; this particular event commonly manifests in
implementing features, notably zooming or scrolling.
Events like dragstart, dragend, dragover, dragenter,
dragleave, and drop are associated with drag-and-
Drag and Drop drop functionality. They allow developers to create
interactive interfaces for dragging elements within a
web page.
Example : Click Event
JavaScript - Mouse Events
In this example we demonstrate the click event. When the button is clicked, it prints an
appropriate message to the console message i.e. “Clicked!”. This event is often used while
submitting forms.

<!DOCTYPE html>
<html>
<head>
<title>Click Event Example</title>
</head>
<body>
<button id="clickButton">Click me!</button>
<p id = "output"></p>
<script>
const clickButton = document.getElementById('clickButton');
const outputDiv = document.getElementById("output");
clickButton.addEventListener('click', function(event) {
outputDiv.innerHTML += 'Clicked!'+ JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>
JavaScript - Mouse Events
Example: Double Click Event
The dblclick event operates in this example, triggering upon a double-click of the designated
button. We attach the event listener to an element with "doubleClickButton" as its id. A user's
double-click on the button prompts a function that logs a console message, confirming their
interaction with it.

<!DOCTYPE html>
<html>
<head>
<title>Double Click Event Example</title>
</head>
<body>
<button id="doubleClickButton">Double-click me!</button>
<p id = "output"></p>
<script>
const doubleClickButton = document.getElementById('doubleClickButton');
const outputDiv = document.getElementById("output");
doubleClickButton.addEventListener('dblclick', function(event) {
outputDiv.innerHTML += 'Double-clicked!' + JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>
JavaScript - Mouse Events

Example: Mouse Down and Mouse Up Events

The use of the mousedown and mouseup events is exemplified in this scenario: both events apply
to a <div> element identified as "mouseUpDownDiv." Two distinct event listeners are established;
one responds to the down action of the mouse button, while another reacts upon release or up
motion of said button.

Upon pressing over the designated div (mousedown), a message indicating that the user has
depressed their mouse button appears within your console log. When the user releases the mouse
button (mouseup), we also log another message to indicate that the mouse button is up.
<!DOCTYPE html> JavaScript - Mouse Events
<html>
<head>
<title>Mouse Down and Mouse Up Events Example</title>
</head>
<body>
<div id="mouseUpDownDiv"
style="width: 600px; height: 100px; background-color: lightblue;">
Please perform mouse down and up event any where in this DIV.
</div>
<p id = "output"></p>
<script>
const mouseUpDownDiv = document.getElementById('mouseUpDownDiv');
const outputDiv = document.getElementById("output");
mouseUpDownDiv.addEventListener('mousedown', function(event) {
outputDiv.innerHTML += 'Mouse button down!' + JSON.stringify(event) + "<br>";
});

mouseUpDownDiv.addEventListener('mouseup', function(event) {
outputDiv.innerHTML += 'Mouse button up!' + JSON.stringify(event) + "<br>";
});
</script>
</body>
</html>
JavaScript - Mouse Events

Example: Mouse Move Event

In this instance, we employ the mousemove event to monitor the mouse pointer's movement
over a specific <div> element identified as "mouseMoveDiv." The handler function extracts
clientX and clientY properties from an event object that represents X-Y coordinates of said
pointer. Subsequently, these are logged into console; thus offering real-time feedback on
where exactly within our designated div area is the user positioning their cursor.
JavaScript - Mouse Events
<!DOCTYPE html>
<html>
<head>
<title>Mouse Move Event Example</title>
</head>
<body>
<div id="mouseMoveDiv"
style="width: 600px; height: 200px; background-color: lightgreen;">
Please move you mouse inside this DIV.</div>
<p id = "output"></p>
<script>
const mouseMoveDiv = document.getElementById('mouseMoveDiv');
const outputDiv = document.getElementById("output");
mouseMoveDiv.addEventListener('mousemove', function(event) {
const x = event.clientX;
const y = event.clientY;
outputDiv.innerHTML += `Mouse moved to (${x}, ${y})` + JSON.stringify(event) +
"<br>";
});
</script>
</body>
</html>
JavaScript - Mouse Events
Example: Wheel Event

This example showcases the wheel event, activated when the mouse wheel is rotated. The
event listener is attached to a <div> element with the id "wheelDiv." When the user rotates
the mouse wheel over this div, the associated function logs a message to the console,
indicating that the mouse wheel has been rotated.
JavaScript - Mouse Events

<!DOCTYPE html>
<html>
<head>
<title>Wheel Event Example</title>
</head>
<body>
<div id="wheelDiv"
style="width: 600px; height: 200px; background-color: palevioletred;">
Please bring the curser inside this DIV and rotate the wheel of mouse.</div>
<p id = "output"></p>
<script>
const wheelDiv = document.getElementById('wheelDiv');
const outputDiv = document.getElementById("output");
wheelDiv.addEventListener('wheel', function(event) {
outputDiv.innerHTML += 'Mouse wheel rotated!'+ event + "<br>";
});
</script>
</body>
</html>
JavaScript - Keyboard Events

The keyboard events in JavaScript provide a way to interact with a web page or application
based on the user's keyboard input. These events allow developers to capture and respond to
various keyboard actions, such as key presses, key releases, and character inputs. The primary
keyboard events in JavaScript include keydown, keypress, and keyup.

Common Keyboard Events

• Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown
event. This event equips developers with information about the specific key that was pressed:
this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or
Alt were also depressed.

• Keypress Event − The keypress event triggers when a user types an actual character. Non-
character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it
to capture user input for form fields or create interactive typing features.

• Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of
a keyup event; this particular event proves beneficial in tracking specific keys' releases and
subsequently implementing actions, thereby creating an interactive user experience.
JavaScript - Keyboard Events
Keyboard Event Properties
For keyboard events in JavaScript, several properties are commonly used to gather information
about the key pressed. Here are some key properties specifically relevant to keyboard events −

Property Description

event.key String representing the key value of the pressed key.

event.code String representing the physical key on the keyboard.

event.location Integer indicating the location of the key on the keyboard.

event.ctrlKey Boolean indicating whether the Ctrl key was held down.

event.shiftKey Boolean indicating whether the Shift key was held down.

event.altKey Boolean indicating whether the Alt key was held down.

Boolean indicating whether the Meta (Command) key was held


event.metaKey
down.
JavaScript - Keyboard Events

Boolean indicating whether the key


event.repeat
event is a repeat event.
Boolean indicating whether the event
event.isComposing is part of a composition of multiple
keystrokes.
Deprecated property; previously used
event.which
to identify the numeric key code.
Method that returns a boolean
event.getModifierState(keyAr
indicating whether the modifier key is
g)
pressed.
JavaScript - Keyboard Events

Example: Keydown Event

This example illustrates the application of JavaScript's keydown event. The event listener
seizes the keydown event upon pressing any key, displaying in an HTML element identified
as "output" - its corresponding key (an event property).

<!DOCTYPE html>
<html>
<body>
<h3>Press any key</h3>
<script>
document.addEventListener('keydown', function (event) {
document.getElementById('output').innerHTML =
"Key pressed: " + event.key;
});
</script>
<div id="output"></div>
</body>
</html>
JavaScript - Keyboard Events

Example: Keypress Event


In this example, the keypress event is utilized to capture a typed character. When a
character is typed, the event listener triggers, and the character is displayed in the HTML
element with the id "output".

<!DOCTYPE html>
<html>
<body>
<h3>Type a character</h3>
<div id="output"></div>
<script>
document.addEventListener('keypress', function (event) {
document.getElementById('output').innerHTML =
"Character pressed: " + event.key;
});
</script>
</body>
</html>
JavaScript - Keyboard Events

Example: Keyup Event


The keyup event is showcased in this example. It captures the event when a key is released
after being pressed. The released key is then displayed on screen.

<!DOCTYPE html>
<html>
<body>
<h3>Press and Release a key</h3>
<div id="output"></div>
<script>
document.addEventListener('keyup', function (event) {
document.getElementById('output').innerHTML =
"Key released: " + event.key;
});
</script>
</body>
</html>
JavaScript - Keyboard Events

There is a difference between keydown and keypress. keydown is triggered when any key
is pressed down, providing information about the pressed key, including modifiers.
keypress is triggered specifically when a character key is pressed, providing information
about the typed character without details on modifiers. Keydown fires continuously as long
as the key is held down.

In all the above examples, we have used the addEventListener but these events can be
listened to without this function as well. This is because of you can assign event handlers
directly to specific properties. However, keep in mind that using addEventListener is
generally considered a better practice because it allows you to attach multiple event
handlers to the same event, and it separates JavaScript logic from the HTML structure.
JavaScript - Keyboard Events

Example: Without using addEventListener method

In this example, we have an input box. When it detects a keydown event (onkeydown), the
handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the
handleKeyUp function. Both the functions print appropriate messages to the screen.
JavaScript - Keyboard Events

<!DOCTYPE html>
<html>
<body>
<div>Enter some text:
<input onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)">
</div>
<div id="output"></div>
<script>
function handleKeyDown(event) {
document.getElementById('output').innerHTML+=
"Key pressed: " + event.key+'<br>Key code: ' +
event.keyCode+'<br>';
}
function handleKeyUp(event) {
document.getElementById('output').innerHTML+=
"Key released: ' + event.key+'<br><br>";
}
</script>
</body>
</html>
JavaScript - Form Events

Form Events

The form events in JavaScript are events that are associated with HTML forms. These events
are triggered by user actions when interacting with form elements like text fields, buttons,
checkboxes, etc. Form events allow you to execute JavaScript code in response to these
actions, enabling you to validate form data, perform actions on form submission or reset,
and enhance the user experience.

JavaScript form events are hooked onto the elements in the Document Object Model also
known as DOM where by default the bubbling propagation is used i.e. from bottom
(children) to top(parent).

List of Common Form Events


Here are some common form events:
JavaScript - Form Events

Form
Description
Event
Triggered when a form is submitted. It's often used for form validation
onsubmit
before data is sent to the server.
Triggered when the form is reset, allowing you to perform actions when
onreset
the user resets the form.
Triggered when the value of a form element (input, select, textarea)
onchange
changes. Commonly used for user input validation or dynamic updates.
Triggered immediately when the value of an input element changes,
oninput
allowing for real-time handling of user input.
Triggered when an element receives focus, such as when a user clicks or
onfocus tabs into an input field. Useful for providing feedback or enhancing the
user experience.
Triggered when an element loses focus, such as when a user clicks outside
onblur an input field or tabs away. Useful for validation or updates triggered by
loss of focus.
JavaScript - Form Events

Examples

Example: The onchange Event

The provided instance below illustrates the functionality of the onchange event. This event
activates upon a user's alteration in dropdown (<select>) option selection. The function,
handleChange, dynamically modifies an <h2> element to display the newly selected country;
thus offering immediate feedback as user preferences evolve.
JavaScript - Form Events
<!DOCTYPE html>
<html>
<body>
<label for="country">Select a country:</label>
<select id="country" onchange="handleChange()">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
</select>
<p id="txt"></p>
<script>
function handleChange() {
// Perform actions when the dropdown selection changes
var selectedCountry = document.getElementById('country').value;
document.getElementById("txt").textContent=
"Selected country: "+selectedCountry;
}
</script>
</body>
</html>
JavaScript - Form Events

Example: The onsubmit Event

The following example highlights the onsubmit event's functionality upon form submission.
The form features a username field and password field; both must be filled for successful
validation when invoking the validateForm function. Upon passing this validation,
submitting the form will trigger display of a confirmation message.
<html>
<body> JavaScript - Form Events
<form onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br/>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// Perform validation
if (username === "" || password === "") {
alert("Please fill in all fields");
return false; // Prevent form submission
}
alert("Form submitted! Username is:"+username+",Password is:"+password);
return true; // Allow form submission
}
</script>
</body>
</html>
JavaScript - Form Events

Example: The onreset event

In this demonstration, we observe the onreset event in action: it triggers upon the user's click of the
"Reset" button within a form. The resetForm function once invoked, clears the form content filled by
user and then displays an alert to confirm successful reset of said form.
JavaScript - Form Events

<!DOCTYPE html>
<html>
<body>
<form onreset="resetForm()">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="reset" value="Reset">
</form>
<script>
function resetForm() {
// Perform actions when the form is reset
alert("Form has been reset!");
}
</script>
</body>
</html>
JavaScript - Form Events

Example: The oninput Event

This example illustrates the oninput event: as the user types into the search input field a
real-time action, indeed! The handleInput function triggers; it logs each current search
input directly to screen.
JavaScript - Form Events

<!DOCTYPE html>
<html>
<body>
<label for="search">Search:</label>
<input type="text" id="search" oninput="handleInput()">
<div id="message" style=" margin-top: 10px; font-weight: lighter;border: 1px solid
#ddd;padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-family: 'Arial',
sans-serif; font-size: 14px; color: #333; width: 30%;"></div>

<script>
var messageElement = document.getElementById('message');
function handleInput() {
// Perform actions as the user types
var searchInput = document.getElementById('search').value;
messageElement.innerHTML+="Search input: " + searchInput+'<br>';
}
</script>
</body>
</html>
JavaScript - Form Events

Example: onfocus and onblur Events

The onfocus and onblur events merge in this example. The user's focus on the input field
triggers a call to the handleFocus function, which then logs a message into the console. In
contrast, when clicks outside of or tabs away from said input field – this action triggers
execution of another function called handleBlur that subsequently records an alternative
message within that same console log.
JavaScript - Form Events

<!DOCTYPE html>
<html>
<body>
<label for="name">Name:</label>
<input type="text" id="name" onfocus="handleFocus()" onblur="handleBlur()">
<p id= "output"></p>
<script>
const output = document.getElementById('output');
function handleFocus() {
// Perform actions when the input gets focus
output.innerHTML += "Input has focus" + "<br>";
}
function handleBlur() {
// Perform actions when the input loses focus
output.innerHTML += "Input lost focus" + "<br>";
}
</script>
</body>
</html>
JavaScript - Window/Document Events

JavaScript window events are actions that occur when the user does something affecting the entire
browser window, like loading, resizing, closing, or moving the window. The most common window
event is simply loading the window by opening a particular web page. This event is handled by
the onload event handler.

Developers can use JavaScript to create dynamic, interactive web pages that respond to user
actions. The interactivity depends on two core aspects: window events and document events.
Operating at the browser's panoramic level, window events bestow control over the overall state
of the browser window; alternatively, document events interact with the HTML document,
empowering developers to react specifically towards elements or actions within a page

Window Events
At the browser level, window events happen and hold association with the window object; this
global object represents the web browser's window. Frequently employed to oversee the overall
state of a browser window or manage global interactions are these types of events.
JavaScript - Window/Document Events

Event
Description
Name
Triggered when the entire web
load page, including all its resources,
has finished loading.
Fired when the user is leaving
unload the page or closing the browser
window or tab.
Activated when the size of the
resize
browser window is changed.
Fired when the user scrolls the
scroll
page.
JavaScript - Window/Document Events

Example: Demonstrating Window Events

In this example, a script actively listens for the 'load,' 'resize,' and 'scroll' events on the window; it
includes an initial page load alert to inform users that loading is complete. Should they
subsequently resize their window, an alert will trigger thereby displaying the new size of their
updated viewport. Moreover, when the user scrolls on the page, an alert is triggered to indicate
their action.
JavaScript - Window/Document Events

<!DOCTYPE html>
<html>
<head>
<title>Window Events Example</title>
<style>
body {
height: 2000px; /* Adding some content just to enable scrolling */
}

#resizeInfo {
position: fixed;
top: 10px;
left: 10px;
background-color: #fff;
padding: 10px;
border: 1px solid #ccc;
}
</style>
JavaScript - Window/Document Events

<script>
window.addEventListener('load', function() {
var initialSizeInfo = 'Initial window size: ' + window.innerWidth + ' x ' +
window.innerHeight;
document.getElementById('resizeInfo').innerText = initialSizeInfo;

alert('The page has finished loading!');


});

window.addEventListener('resize', function() {
var newSizeInfo = 'New window size: ' + window.innerWidth + ' x ' +
window.innerHeight;
document.getElementById('resizeInfo').innerText = newSizeInfo;
alert("Page has been resized");
});
JavaScript - Window/Document Events

window.addEventListener('scroll', function() {
alert('You have scrolled on this page.');
},{once:true});
</script>
</head>
<body>
<div id="resizeInfo">Initial window size:
${window.innerWidth} x ${window.innerHeight}</div>
</body>
</html>
JavaScript - Window/Document Events

Document Events
Document events on the other hand occur at the level of the HTML document within the window
and are associated with the document object which represents the HTML document thereby
providing an interface to interact with the content of the page.

Event Name Description

Triggered when the HTML document has been


DOMContentLoaded completely loaded and parsed, without waiting for
external resources like images.

click Fired when the user clicks on an element.

submit Triggered when a form is submitted.

These events are triggered when a key is pressed,


keydown/keyup/keypress
released, or both, respectively.

Fired when the value of an input element changes,


change
such as with text inputs or dropdowns.
JavaScript - Window/Document Events

Example: Demonstrating Document Events

In this example, we've included a script that listens for the 'DOMContentLoaded,' 'click,' 'submit,'
and 'keydown' events on the document. Upon the 'DOMContentLoaded' event, it logs to the
console that the DOM content has been fully loaded.

Subsequently, clicking an element triggers an alert displaying the tag name of the clicked
element. Submitting a form also alerts that the form has been submitted. Furthermore, pressing a
key like entering the username with characters, alerts every keypress to the screen.
JavaScript - Window/Document Events

<!DOCTYPE html>
<html>
<head>
<title>Document Events Example</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
alert('DOM content has been fully loaded!');
});

document.addEventListener('click', function(event) {
alert('Element clicked! Tag Name: ' + event.target.tagName);
},{once:true});

document.addEventListener('submit', function() {
alert('Form submitted!');
});
JavaScript - Window/Document Events

document.addEventListener('keydown', function(event) {
alert('Key pressed: ' + event.key);
},{once:true});
</script>
</head>
<body>
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<button type="submit">Submit</button>
</form>
</body>
</html>
JavaScript - Browser Object Model

The Browser Object Model (BOM) in JavaScript refers to the objects provided by the
browsers to interact with them. By using these objects, you can manipulate the browser's
functionality. For example, you can get the browser history and window size, navigate to
different URLs, etc.

The Browser object model is not standardized. It depends on which browser you are
using.

Here, we have listed all objects of the Browser Object Model with descriptions −
JavaScript - Browser Object Model

•Window − The 'window' object represents the current browser window. You
can use it to manipulate the browser window.

•Document − The 'document' object represents the currently opened web


page in the browser window. You can use it to customize the property of the
document.

•Screen − It provides information about the user's device's screen.

•History − It provides the browser's session history.

•Navigator − It is used to get the browser's information like default


language, etc.

•Location − The Location object is used to get the URL information, such as
the hostname of the current web page.

•Console − The console object allows developers to access the browser's


console.
JavaScript - Browser Object Model

•JavaScript Window Object

•The JavaScript window object represents the browser's window. We can use different methods
and properties of the window object to manipulate current browser window. For example,
showing an alert, opening a new window, closing the current window, etc.

•All the JavaScript global variables are properties of window object. All global functions are
methods of the window object.

•The other objects listed above such as document, screen, history etc., are the properties of the
window object. We can access these objects as properties of the window object. We can also
access them with referencing the window object. Look at the below example snippet to access
the document object –

•window.document.write("Welcome to Tutorials Point");


•or without window object −

•document.write("Welcome to Tutorials Point");


JavaScript - Browser Object Model

•The innerHeight and innerWidth properties of the window object are used to
access the height and width of the browser window. We will learn JavaScript
window object in detail in next chapters.

JavaScript Document Object

The document object is a property of the JavaScript window object. The


whole HTML document is represented as a document object. The document
object forms HTML DOM. It is root node of the HTML document.
The document object can be accessed as window.document or
just document.

The document object provides us with many properties and methods to


access the HTML elements and manipulate them. One such method is
document.getElementById() to access the HTML element using its id.
We can access an element with id as "text" using getElementById() method
and manipulate it –
JavaScript - Browser Object Model

Example

<html>
<body>
<div id ="text">This text will be changed. </div>
<script>
// Access the element with id as text
const textDiv = document.getElementById("text");
// Change the content of this element
textDiv.innerHTML = "The text of this DIV is changed.";
</script>
</body>
</html>

Output
The text of this DIV is changed.
JavaScript - Browser Object Model

JavaScript Screen Object

In JavaScript, the screen object is a property of window object. It provides


us with properties that can be used to get the information about the device
window screen. We can access the screen object as window.screen or
just screen.

To get the width and height of the device screen in pixels we can use
the screen.width and screen.height properties –
Example
JavaScript - Browser Object Model

Example

<html>
<body>
<div id ="width">Width of the device screen is </div>
<div id ="height">Height of the device screen is </div>
<script>
document.getElementById("width").innerHTML += screen.width + " px.";
document.getElementById("height").innerHTML += screen.height + " px.";
</script>
<p> The above result may be different for different device.</p>
</body>
</html>

Output
Width of the device screen is 1536 px.
Height of the device screen is 864 px.
The above result may be different for different device.
JavaScript - Browser Object Model

JavaScript History Object

In JavaScript, the history object is also a property of the window object. It


contains a list of the visited URLs in the current session. The history object
provides an interface to manipulate the browser's session history.

The JavaScript history object can be accessed using window.history or


just history. We can use the methods of history object to navigate the URLs
in the history list. For example to go the previous page/URL in the history
list, we can use history.back() method.
JavaScript - Browser Object Model

JavaScript Navigator Object

The JavaScript navigator object is also a property of the window object.


Using the 'navigator' object, you can get the browser version and name and
check whether the cookie is enabled in the browser. We can access the
navigator object using window.navigator. We can also access it without
using the window prefix.

JavaScript Location Object

The JavaScript 'location' object contains various properties and methods to


get and manipulate the information of the browser's location, i.e. URL. It's
also a property of JavaScript window object.

We can use the properties and methods of the location object to manipulate
the URL information. For example, to get the host from the current URL, we
can use the window.location.host or just location.host. The host is property
of the location object.
JavaScript - Browser Object Model

<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The host of the current location is: " + location.host;
</script>
</body>
</html>

Output
The host of the current location is:_______________________
JavaScript - Browser Object Model

JavaScript Console Object

The JavaScript console object allows us to access the debugging console of


the browser. It is a property of the JavaScript window object. It can be
accessed using window.console or just console.

The console object provides us with different methods such as console.log().


The console.log() method is used to display the message in debugging
console.
JavaScript - Form Validations

Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the client
and request that the form be resubmitted with correct information. This was really a lengthy
process which used to put a lot of burden on the server.

JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.

Basic Validation − First of all, the form must be checked to make sure all the mandatory fields
are filled in. It would require just a loop through each field in the form and check for data.

Data Format Validation − Secondly, the data that is entered must be checked for correct form
and value. Your code must include appropriate logic to test correctness of data.
JavaScript - Form Validations
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"


method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
JavaScript - Form Validations
JavaScript - Form Validations
JavaScript - Form Validations

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/> <br/>
Password: <input type="password" name="password"><br/> <br/>
<input type="submit" value="register">
</form>
JavaScript - Form Validations
JavaScript - Form Validations
JavaScript - Form Validations
JavaScript - Form Validations
JavaScript Retype Password Validation
<script type="text/javascript">

function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


Password: <input type="password" name="password" /><br/> <br/>
Re-enter Password: <input type="password" name="password2"/><br/> <br/>
<input type="submit">
</form>
JavaScript - Form Validations
JavaScript Retype Password Validation
JavaScript - Form Validations
JavaScript Retype Password Validation
JavaScript - Form Validations
Example
We will take an example to understand the process of validation. Here is a
simple form in html format.

<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
// Form validation code will come here.

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;
}
JavaScript - Form Validations

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 );
}
</script>
</head>
JavaScript - Form Validations
<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>
JavaScript - Form Validations

<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>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>
JavaScript - Form Validations
JavaScript - Form Validations
JavaScript - Number Validation
JavaScript Can Validate Numeric Input
JavaScript is often used to validate numeric input:

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
JavaScript - Number Validation
JavaScript - Number Validation
JavaScript - Number Validation

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

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

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

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

<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
JavaScript - Number Validation

// If x is Not a Number or less than one or greater than 10


let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>
JavaScript - Number Validation
JavaScript - Number Validation
Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being submitted:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>
Automatic HTML Form Validation
Automatic HTML Form Validation
JavaScript email validation

We can validate the email by the help of JavaScript.


There are many criteria that need to be follow to validate the email id such as:

• email id must contain the @ and . character


• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.


JavaScript email validation

We can validate the email by the help of JavaScript.


There are many criteria that need to be follow to validate the email id such as:

• email id must contain the @ and . character


• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.


JavaScript email validation
<script>

function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n
atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>

<form name="myform" method="post" action="#" onsubmit="return


validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
JavaScript email validation
JavaScript email validation
JavaScript Sign In Form

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

body{
background-color: #021012;
font-family: sans-serif;
}
JavaScript Sign In Form
.formContainer{
width: 80%;
height: 85vh;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: #E2F4FD;
}
header{
text-align: center;
margin: 2rem 0;
font-weight: 600;
}

#myForm{
width: 90%;
margin: 1rem auto;
}

.formDetails{
margin: 1rem 0;
}
label{ JavaScript Sign In Form
display: block;
font-size: 1rem;
font-weight: 600;
margin-bottom: .4rem;
}
input{
width: 100%;
padding: .6rem 0;
outline: none;
font-size: 1rem;
}
input:focus{
outline: 1px solid #064247;
}
button{
margin: 1.1rem 0;
background-color: #053135;
color: #fff;
font-weight: 600;
border: none;
padding: .8rem 0;
width: 100%;
}
JavaScript Sign In Form
.errorMessage{
margin-top: .3rem;
font-size: .9rem;
font-weight: 600;
font-family: monospace;
}
.formDetails.success input {
border-color: #09c372;
outline: none;
}

.formDetails.error input {
border-color: #f2070e;
}

@media screen and (min-width: 1024px) {


.formContainer{
width: 30%;
}
}
</style>
</head>
JavaScript Sign In Form

<body>
<div class="formContainer">
<header>
<h1>Sign In</h1>
</header>

<form id="myForm">
<div class="formDetails">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<div class="errorMessage"></div>
</div>

<div class="formDetails">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<div class="errorMessage"></div>
</div>
JavaScript Sign In Form

<div class="formDetails">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div class="errorMessage"></div>
</div>

<div class="formDetails">
<label for="confirmpassword">Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmpassword">
<div class="errorMessage"></div>
</div>

<button id="button" type="submit">Submit</button>


</form>
</div>
</body>
</html>
JavaScript Sign In Form

<script>
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (event) => {
event.preventDefault(); // prevent form submission

//Validate for name


const name = myForm.elements.name.value.trim();
const nameError = document.querySelector('#name + .errorMessage');
const nameInput = document.getElementById('name');
if (name === '') {
nameError.textContent = 'Name is required.';
nameInput.parentNode.classList.add('error');
nameInput.parentNode.classList.remove('success');
} else {
nameError.textContent = '';
nameInput.parentNode.classList.add('success');
nameInput.parentNode.classList.remove('error');
}
JavaScript Sign In Form

//Validate for email


const email = myForm.elements.email.value.trim();
const emailError = document.querySelector('#email + .errorMessage');
const emailInput = document.getElementById('email');
if (email === '') {
emailError.textContent = 'Email is required.';
emailInput.parentNode.classList.add('error');
emailInput.parentNode.classList.remove('success');
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
emailError.textContent = 'Please enter a valid email address.';
emailInput.parentNode.classList.add('error');
emailInput.parentNode.classList.remove('success');
} else {
emailError.textContent = '';
emailInput.parentNode.classList.add('success');
emailInput.parentNode.classList.remove('error');
}
JavaScript Sign In Form

//Validate password
const password = myForm.elements.password.value.trim();
const passwordError = document.querySelector('#password + .errorMessage');
const passwordInput = document.getElementById('password');
if (password === '') {
passwordError.textContent = 'Password is required.';
passwordInput.parentNode.classList.add('error');
passwordInput.parentNode.classList.remove('success');
} else if (password.length < 8) {
passwordError.textContent = 'Password is expected to be 8 characters.';
passwordInput.parentNode.classList.add('error');
passwordInput.parentNode.classList.remove('success');
} else {
passwordError.textContent = '';
passwordInput.parentNode.classList.add('success');
passwordInput.parentNode.classList.remove('error');
}
JavaScript Sign In Form

//Validate confirm password


const confirmPassword = myForm.elements.confirmpassword.value.trim();
const confirmPasswordError = document.querySelector('#confirmPassword + .errorMessage');
const confirmPasswordInput = document.getElementById('confirmPassword');
if (confirmPassword === '') {
confirmPasswordError.textContent = 'Confirm Password is required.';
confirmPasswordInput.parentNode.classList.add('error');
confirmPasswordInput.parentNode.classList.remove('success');
} else if (confirmPassword !== password) {
confirmPasswordError.textContent = 'Passwords do not match.';
confirmPasswordInput.parentNode.classList.add('error');
confirmPasswordInput.parentNode.classList.remove('success');
} else {
confirmPasswordError.textContent = '';
confirmPasswordInput.parentNode.classList.add('success');
confirmPasswordInput.parentNode.classList.remove('error');
}
JavaScript Sign In Form

//Submit the form if there are no errors

if (nameError.textContent === '' && emailError.textContent === '' &&


passwordError.textContent === '' && confirmPasswordError.textContent === '') {
myForm.submit();
}
});
</script>
JavaScript Sign In Form
JavaScript Sign In Form
JavaScript Sign In Form
Create A Password Validation Form
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style all input fields */
input {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}

/* Style the submit button */


input[type=submit] {
background-color: #04AA6D;
color: white;
}
Create A Password Validation Form

/* Style the container for inputs */


.container {
background-color: #f1f1f1;
padding: 20px;
}

/* The message box is shown when the user clicks on the password field */
#message {
display:none;
background: #f1f1f1;
color: #000;
position: relative;
padding: 20px;
margin-top: 10px;
}

#message p {
padding: 10px 35px;
font-size: 18px;
}
Create A Password Validation Form
/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}
.valid:before {
position: relative;
left: -35px;
content: "✔";
}

/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
color: red;
}

.invalid:before {
position: relative;
left: -35px;
content: "✖";
}
</style>
</head>
Create A Password Validation Form

<body>

<h3>Password Validation</h3>
<p>Try to submit the form.</p>

<div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>

<label for="psw">Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8
or more characters" required>

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


</form>
</div>
Create A Password Validation Form

<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>

<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");

// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
Create A Password Validation Form

// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}

// When the user starts to type something inside the password field

myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
Create A Password Validation Form

// Validate capital letters


var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}

// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
Create A Password Validation Form

// Validate length

if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>

</body>
</html>
Create A Password Validation Form
Create A Password Validation Form
Create A Password Validation Form
Create A Password Validation Form
Regular Expressions

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search
pattern.

When you search for data in a text, you can use this search pattern to
describe what you are searching for.

A regular expression can be a single character, or a more complicated


pattern.

Regular expressions can be used to perform all types of text search and
text replace operations.
Regular Expressions

A regular expression (RegExp) in JavaScript is an object that describes a pattern of characters.


It can contain the alphabetical, numeric, and special characters. Also, the regular expression
pattern can have single or multiple characters.

The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-
replace functions on text.

The regular expression is used to search for the particular pattern in the string or replace the
pattern with a new string.

There are two ways to construct the regular expression in JavaScript.

• Using the RegExp() constructor.

• Using the regular expression literal.


Regular Expressions

Syntax
A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);


or simply
var pattern = /pattern/attributes;

Parameters
Here is the description of the parameters −

• pattern − A string that specifies the pattern of the regular expression or another regular
expression.

• attributes − An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multi-line matches, respectively.

Before we learn examples of regular expression, let's learn about regular expression modifiers,
Quantifiers, literal characters, etc.
Regular Expressions
Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in
multiple lines, etc.

Sr.No. Modifier & Description

i
1
Perform case-insensitive matching.

m
Specifies that if the string has newline or carriage
2 return characters, the ^ and $ operators will now
match against a newline boundary, instead of a string
boundary

g
3 Performs a global matchthat is, find all matches
rather than stopping after the first match.
Regular Expressions

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a case-insensitive search for "Javascript" in a string:</p>

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

<script>
let text = "Visit Javascript Tutorial";
let result = text.match(/Javascript/i);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Regular Expressions

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for "is" in a string:</p>

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

<script>
let text = "Is this all there is?";
let result = text.match(/is/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Regular Expressions
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of
characters.

The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through
3, or the range [b-v] to match any lowercase character ranging from b through v.

Sr.No. Expression & Description


[...]
1
Any one character between the brackets.
[^...]
2
Any one character not between the brackets.
[0-9]
3
It matches any decimal digit from 0 through 9.
[a-z]
4 It matches any character from lowercase a through
lowercase z.
[A-Z]
5 It matches any character from uppercase A through
uppercase Z.
[a-Z]
6 It matches any character from lowercase a through
uppercase Z.
Regular Expressions

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for the character "h" in a string:</p>

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

<script>
let text = "Is this all there is?";
let result = text.match(/[h]/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Regular Expressions

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Regular Expressions</h1>

<p>Do a global search for the numbers 1 to 4 in a string:</p>

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

<script>
let text = "123456789";
let result = text.match(/[1-4]/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Regular Expressions

Quantifiers

The frequency or position of bracketed character sequences and single


characters can be denoted by a special character. Each special character has
a specific connotation. The +, *, ?, and $ flags all follow a character
sequence.
Regular Expressions

Sr.No. Expression & Description


p+
1
It matches any string containing one or more p's.
p*
2
It matches any string containing zero or more p's.
p?
3
It matches any string containing at most one p.
p{N}
4
It matches any string containing a sequence of N p's
p{2,3}
5 It matches any string containing a sequence of two or
three p's.
p{2, }
6 It matches any string containing a sequence of at
least two p's.
p$
7
It matches any string with p at the end of it.
^p
8
It matches any string with p at the beginning of it.
?!p
9 It matches any string which is not followed by a string
p.
Regular Expressions
Examples

Following examples explain more about matching characters.

Sr.No. Expression & Description


[^a-zA-Z]
It matches any string not containing any of the
1
characters ranging
from a through z and A through Z.

p.p
2 It matches any string containing p, followed by
any character, in turn followed by another p.

^.{2}$
3 It matches any string containing exactly two
characters.
<b>(.*)</b>
4 It matches any string enclosed within <b> and
</b>.
p(hp)*
5 It matches any string containing a p followed by
zero or more instances of the sequence hp.
Regular Expressions

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for at least one "o" in a string:</p>

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

<script>
let text = "Hellooo World! Hello W3Schools!";
let result = text.match(/o+/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Literal characters
Regular Expressions
The literal characters can be used with a backslash (\) in the regular expression. They are used
to insert special characters, such as tab, null, Unicode, etc., in the regular expression.

Sr.No. Character & Description


Alphanumeric
1
Itself
\0
2
The NUL character (\u0000)
\t
3
Tab (\u0009
\n
4
Newline (\u000A)
\v
5
Vertical tab (\u000B)
\f
6
Form feed (\u000C)
Regular Expressions

\r
7
Carriage return (\u000D)

\xnn
The Latin character specified by the
8
hexadecimal number nn; for example,
\x0A is the same as \n

\uxxxx
The Unicode character specified by the
9
hexadecimal number xxxx; for example,
\u0009 is the same as \t

\cX
The control character ^X; for example,
10
\cJ is equivalent to the newline
character \n
Regular Expressions

Metacharacters

A metacharacter is simply an alphabetical character preceded by a


backslash that acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d'
metacharacter: /([\d]+)000/, Here \d will search for any string of numerical
character.

The following table lists a set of metacharacters which can be used in PERL
Style Regular Expressions.
Regular Expressions

Sr.No. Character & Description

.
1
a single character
\s
2
a whitespace character (space, tab, newline)
\S
3
non-whitespace character
\d
4
a digit (0-9)
\D
5
a non-digit
\w
6
a word character (a-z, A-Z, 0-9, _)
\W
7
a non-word character
[\b]
8
a literal backspace (special case).
Regular Expressions

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Do a global search for digits in a string:</p>

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

<script>
let text = "Give 100%!";
let result = text.match(/\d/g);
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>
Regular Expressions
Regular Expressions
Let's learn to create regular expressions below.

let exp = / javascript/I

• / javascript/– It finds a match for the ' javascript ' string.

• i – It ignores the case of the characters while matching the pattern with the string. So, it
matches with ' JavaScript ', or ‘JAVAscript', etc.

let exp = /\d+/

• \d – It matches 0 to 9 digits.

• + – It matches one or more numeric digits.

let exp = /^Hi/

• ^ - It matches the start of the text.

• Hi – It checks whether the text contains 'Hi' at the start.


Regular Expressions
Let exp = /^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/

The above regular expression validates the email. It looks complex, but it
is very easy to understand.

• ^ - Start of the email address.


• [a-zA-Z0-9] – It should contain the alphanumeric characters in the start.
• + - It should contain at least one alphanumeric character.
• @ - It must have the '@' character after the alphanumeric characters.
• [a-zA-Z]+ - After the '@' character, it must contain at least 1
alphanumeric character.
• \. – It must contain a dot after that.
• [a-zA-Z] – After the dot, the email should contain alphabetical
characters.
• {2, 3} – After the dot, it should contain only 2 or 3 alphabetical
characters. It specifies the length.
• $ - It represents the end of the pattern.
Regular Expressions
Now, the question is whether we can use the search() or replace() method
to search or replace text in the string by passing the string as an
argument; then what is the need for the regular expression?
The question is obvious. Let's understand it via the example below.

Example
In the below example, we used the regular expression literal to define
the regular expression. The pattern matches the 'tutorialspoint' string
without comparing the case of characters.

In the first case, the string search() method searches for the
'tutorialspoint' string, which performs the case-sensitive match. So, it
returns -1.

In the second case, we passed the regular expression as an argument


of the search() method. It performs the case-insensitive match. So, it
returns 11, the index of the required pattern.
Regular Expressions
<html>
<head>
<title> JavaScript - Regular Expression </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
let pattern = /tutorialspoint/i;
let str = "Welcome to TuTorialsPoint! It is a good website!";
let res = str.search('tutorialspoint');
output.innerHTML += "Searching using the string : " + res + "<br>";
res = str.search(pattern);
output.innerHTML += "Searching using the regular expression : " +
res;
</script>
</body>
Regular Expressions
Regular Expressions

Example

In the example below, we used the replace() method to match the pattern
and replace it with the '100' string.

Here, the pattern matches the pair of digits. The output shows that each
number is replaced with '100' in the string. You may also add alphabetical
characters in the string.
Regular Expressions

<html>
<head>
<title> JavaScript - Regular expression </title>
</head>
<body>
<p id = "output"> </p>
<script>
let pattern = /\d+/g; // Matches pair of digits
let str = "10, 20, 30, 40, 50";

let res = str.replace(pattern, "100");


document.getElementById("output").innerHTML =
"String after replacement : " + res;
</script>
</body>
</html>
Regular Expressions
Regular Expressions

Example (Email validation)

In the example below, we used the RegExp() constructor function with a


'new' keyword to create a regular expression. Also, we have passed the
pattern in the string format as an argument of the constructor.

Here, we validate the email using the regular expression. In the first case,
email is valid. In the second case, the email doesn't contain the ‘@’
character, so the test() method returns false.
Regular Expressions

<html>
<body>
<p id = "output"> </p>
<script>
const pattern = new RegExp('^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-
Z]{2,3}$');
document.getElementById("output").innerHTML =
"[email protected] is valid? : " +
pattern.test('[email protected]') + "<br>" +
"abcdgmail.com is valid? : " + pattern.test('abcdgmail.com');
</script>
</body>
</html>
Regular Expressions
Regular Expressions

So, the regular expression can be used to find a particular


pattern in the text and perform operations like replace.
Regular Expressions
RegExp Properties

Here is a list of the properties associated with RegExp and their description.

Sr.No. Property & Description

constructorSpecifies the function that creates


1
an object's prototype.

2 globalSpecifies if the "g" modifier is set.

3 ignoreCaseSpecifies if the "i" modifier is set.

lastIndexThe index at which to start the next


4
match.

5 multilineSpecifies if the "m" modifier is set.

6 sourceThe text of the pattern.


Regular Expressions
JavaScript - RegExp global Property

Description

global is a read-only boolean property of RegExp objects. It specifies whether a particular


regular expression performs global matching, i.e., whether it was created with the "g" attribute.

Syntax
Its syntax is as follows −

RegExpObject.global

Return Value

Returns "TRUE" if the "g" modifier is set, "FALSE" otherwise.


Example
Regular Expressions
Try the following example program.
<html>
<head>
<title>JavaScript RegExp global Property</title>
</head>
<body>
<script type = "text/javascript">
var re = new RegExp( "string" );

if ( re.global ) {
document.write("Test1 - Global property is set");
} else {
document.write("Test1 - Global property is not set");
}
re = new RegExp( "string", "g" );

if ( re.global ) {
document.write("<br />Test2 - Global property is set");
} else {
document.write("<br />Test2 - Global property is not set");
}
</script>
</body>
Regular Expressions
Regular Expressions
RegExp Methods

Here is a list of the methods associated with RegExp along with their description.

Sr.No. Method & Description


exec()Executes a search for a match
1
in its string parameter.
test()Tests for a match in its string
2
parameter.
toSource()Returns an object literal
representing the specified object;
3
you can use this value to create a
new object.
toString()Returns a string
4
representing the specified object.
JavaScript - RegExp exec Method

The JavaScript RegExp.exec() method is used to search a string for a specified pattern
defined by the regular expression. If the match is found, it returns an array with the matched
text, otherwise, it will return null in the result.

In JavaScript, a regular expression (RegExp) is an object that describes a sequence of


characters used for defining a search pattern. The best use of regular expressions is for form
validation. When users submit data through forms (such as input fields), you can apply regular
expressions to ensure that the data meets specific criteria.

Syntax
Following is the syntax of JavaScript RegExp.exec() method −

RegExp.exec(str)

Parameters
This method accepts a parameter named 'str', which is described below −

• str − The string needs to be searched.


JavaScript - RegExp exec Method

Return value
This method returns an array containing the matched text, If a match is found. Otherwise, it
will return a null value.

Examples
If a match is found, this method will return an array that contains the matched text.

Example 1
In the following example, we are using the JavaScript RegExp.exec() method to search a string
for a pattern ('to*', 'g') defined by the regular expression within the string " Tutorials
Javascript ".
JavaScript - RegExp exec Method

<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('to*', 'g');
const str = "Tutorials Javascript";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>An array with matched text: ", arr);
document.write("<br>The array length: ", arr.length);
</script>
</body>
</html>
JavaScript - RegExp exec Method
JavaScript - RegExp exec Method

Example 2
If there is no match found, the method will return null.

The following is another example of the JavaScript RegExp.exec()


method. We use this method to search a string for a pattern ('/mn\*',
'g') defined by the regular expression within this string "Virat is a damn
good batsman".
JavaScript - RegExp exec Method

<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('/mn\*', 'g');
const str = "Virat is a damn good batsman";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let arr = {};
arr = regex.exec(str);
document.write("<br>An array with matched text: ", arr);
document.write("<br>The array length: ", arr.length);
</script>
</body>
</html>
JavaScript - RegExp exec Method
JavaScript - RegExp exec Method

Example 3
We can use the result of this method in the conditional statement to check whether a match is
found or not.
JavaScript - RegExp exec Method
<html>
<head>
<title>JavaScript RegExp.exec() Method</title>
</head>
<body>
<script>
const regex = RegExp('\llo*', 'g');
const str = "Hello World";
document.write("The string to be searched: ", str);
document.write("<br>The regex: ", regex);
let result = {};
result = regex.exec(str);

//using method result in conditional statement....


if(result != null){
document.write("<br>The string '" + result[0] + "' found.")
} else {
document.write("<br>Not found...");
}
</script>
</body>
</html>
JavaScript - RegExp exec Method

You might also like