Unit No.2 Client-Side Scripting
Unit No.2 Client-Side Scripting
JavaScript Objects
Object Properties
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 objects have the same methods, but the methods are performed at different times.
JavaScript Variables
JavaScript Objects
JavaScript variables are containers for data values.
<!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"};
</body>
</html>
JavaScript Objects
Output:
JavaScript Objects
Creating an Object
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"};
</body>
</html>
JavaScript Object Definition
Output:
Creating JavaScript Objects
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";
</body>
</html>
JavaScript Object Definition
Output:
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
};
</body>
</html>
JavaScript Object Definition
Output:
JavaScript Objects
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
};
</body>
</html>
JavaScript Object Definition
Output:
JavaScript Objects
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
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 −
•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.’
•hour − Integer value representing the hour of the day (24-hour scale).
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
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.
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
Static Methods
The static methods are invoked using the 'String' class itself.
Examples
Let's take understand the JavaScript String object and string primitives with the
help of some examples.
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 −
Parameters
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 −
You will use ordinal numbers to access and to set values inside an array as
follows.
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
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
Output
Execute the above program to see the desired output.
<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
Execute the above program to see the desired output.
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.
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.
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 −
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 −
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.
Syntax
The syntax for creating a number object is as follows −
We can also create the number primitives by assigning the numeric values to the variables −
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.
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
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.
<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.
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.
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 −
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
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
Whenever any event triggers, it invokes the inline JavaScript code or executes the callback
function to perform the particular action.
Syntax
Users can follow the syntax below to use event handlers with HTML elements.
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.
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
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:
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
• Change − This event occurs when the value of an HTML element is changed.
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.
<!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
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
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.
• 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.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.
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
<!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
<!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
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).
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
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
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
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
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
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
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;
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.
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.
•Location − The Location object is used to get the URL information, such as
the hostname of the current web page.
•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 –
•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.
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
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
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
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>
<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>
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
// Form validation code will come here.
function validate() {
<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>
<input id="numb">
<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
</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>
<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
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>
<!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;
}
<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>
<script>
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (event) => {
event.preventDefault(); // prevent form submission
//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
/* 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>
<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 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
When you search for data in a text, you can use this search pattern to
describe what you are searching for.
Regular expressions can be used to perform all types of text search and
text replace operations.
Regular Expressions
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.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
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.
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>
<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>
<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.
<!DOCTYPE html>
<html>
<body>
<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 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
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>
<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.
\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
The following table lists a set of metacharacters which can be used in PERL
Style Regular Expressions.
Regular Expressions
.
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>
<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.
• i – It ignores the case of the characters while matching the pattern with the string. So, it
matches with ' JavaScript ', or ‘JAVAscript', etc.
• \d – It matches 0 to 9 digits.
The above regular expression validates the email. It looks complex, but it
is very easy to understand.
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.
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";
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
Here is a list of the properties associated with RegExp and their description.
Description
Syntax
Its syntax is as follows −
RegExpObject.global
Return Value
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.
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.
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 −
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.
<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);