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

UNIT 2 JavaScript

The document provides an overview of JavaScript, highlighting its features, such as client-side scripting, versatility, and asynchronous capabilities. It also explains the Document Object Model (DOM), JavaScript variables, data types, and operators, detailing how to declare variables and the different types of data in JavaScript. Additionally, it covers the various operators available in JavaScript, including arithmetic, comparison, and logical operators.

Uploaded by

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

UNIT 2 JavaScript

The document provides an overview of JavaScript, highlighting its features, such as client-side scripting, versatility, and asynchronous capabilities. It also explains the Document Object Model (DOM), JavaScript variables, data types, and operators, detailing how to declare variables and the different types of data in JavaScript. Additionally, it covers the various operators available in JavaScript, including arithmetic, comparison, and logical operators.

Uploaded by

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

1

UNIT 2 JavaScript
Introduction:-
JavaScript is a versatile, dynamically typed programming language that brings
life to web pages by making them interactive. It is used for building interactive
web applications, supports both client-side and server-side development, and
integrates seamlessly with HTML, CSS, and a rich standard library.

 JavaScript is a single-threaded language that executes one task at a time.


 It is an interpreted language which means it executes the code line by line.
 The data type of the variable is decided at run-time in JavaScript, which is
why it is called dynamically typed.

Features of JavaScript
Here are some key features of JavaScript that make it a powerful language for
web development:
 Client-Side Scripting: JavaScript runs on the user's browser, so has a faster
response time without needing to communicate with the server.
 Versatile: Can be used for a wide range of tasks, from simple calculations to
complex server-side applications.
 Event-Driven: Responds to user actions (clicks, keystrokes) in real-time.
 Asynchronous: It can handle tasks like fetching data from servers without
freezing the user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built on
JavaScript, such as React, Angular, and [Link], which make development
faster and more efficient.

PDVP collage Tasgaon Mr. J.H. Lawand


2

Document Object Model


Introduction:-
The HTML DOM (Document Object Model) is a structured representation of
a web page that allows developers to access, modify, and control its content and
structure using JavaScript. It powers most dynamic website interactions, enabling
features like real-time updates, form validation, and interactive user interfaces.

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

The HTML DOM Tree of Objects

 The HTML Document Object Model (DOM) is a tree structure, where each
HTML tag becomes a node in the hierarchy.
 At the top, the <html> tag is the root element, containing
both <head> and<body> as child elements.
 These in turn have their own children, such as <title>, <div>, and nested
elements like <h1>, <p>,<ul>, and<li>.
 Elements that contain other elements are labeled as container elements, while
elements that do not are simply child elements.
 This hierarchy allows developers to navigate and manipulate web page
content using JavaScript by traversing from parent to child and vice versa.
Properties of the DOM
 Node-Based: Everything in the DOM is represented as a node (e.g., element
nodes, text nodes, attribute nodes).

PDVP collage Tasgaon Mr. J.H. Lawand


3

 Hierarchical: The DOM has a parent-child relationship, forming a tree


structure.
 Live: Changes made to the DOM using JavaScript are immediately reflected
on the web page.
 Platform-Independent: It works across different platforms, browsers, and
programming languages.

Types of DOM
The DOM is seperated into 3 parts:
 Core DOM: It is standard model for all document types(All DOM
implementations must support the interfaces listed as "fundamental" in the
code specifications).
 XML DOM: It is standard model for XML Documents( as the name suggests,
all XML elements can be accessed through the XML DOM .)
 HTML DOM: It is standard model for HTML documents (The HTML DOM
is a standard for how to get, change, add, or delete HTML elements.)

JavaScript Variables
Variables in JavaScript can be declared using var, let, or const. JavaScript is
dynamically typed, so variable types are determined at runtime without explicit
type definitions.
// Old style
var a = 10

// Prferred for non-const


let b = 20;

// Preferred for const (cannot be changed)


const c = 30;

[Link](a);
[Link](b);
[Link](c);

Output
10
20
30

Declaring Variables in JavaScript


 Before ES6 (2015): Variables were declared only with var, which is function-
scoped and global-scoped, causing issues like hoisting and global pollution.

PDVP collage Tasgaon Mr. J.H. Lawand


4

 ES6 Introduction: let and const were introduced to provide safer alternatives for
declaring variables.
 Scope: let and const are block-scoped (limited to { } block) or global-scoped,
reducing errors compared to var.

1. var keyword
var is a keyword in JavaScript used to declare variables and it is Function-
scoped and hoisted, allowing redeclaration but can lead to unexpected bugs.
var a = "Hello Geeks";
var b = 10;
[Link](a);
[Link](b);

2. let keyword
let is a keyword in JavaScript used to declare variables and it is Block-scoped and
not hoisted to the top, suitable for mutable variables
let a = 12
let b = "gfg";
[Link](a);
[Link](b);

3. const keyword
const is a keyword in JavaScript used to declare variables and it is Block-scoped,
immutable bindings that can't be reassigned, though objects can still be mutated.
const a = 5
let b = "gfg";
[Link](a);
[Link](b);

Rules for Naming Variables


When naming variables in JavaScript, follow these rules
 Variable names must begin with a letter, underscore (_), or dollar sign ($).
 Subsequent characters can be letters, numbers, underscores, or dollar signs.
 Variable names are case-sensitive (e.g., age and Age are different variables).
 Reserved keywords (like function, class, return, etc.) cannot be used as variable
names.
let userName = "Suman"; // Valid
let $price = 100; // Valid
let _temp = 0; // Valid
let 123name = "Ajay"; // Invalid
let function = "gfg"; // Invalid

JavaScript Data Type


JavaScript data types determine the nature of data stored in variables, affecting
how values are processed and interacted with in the code. Each data type has

PDVP collage Tasgaon Mr. J.H. Lawand


5

specific properties and behavior that impact how data is stored, accessed,
and manipulated.

JavaScript Data Type Categories


JavaScript data types are categorized into Primitive and Non-Primitive types

Primitive Data Type


Primitive data types in JavaScript represent simple, immutable values stored
directly in memory, ensuring efficiency in both memory usage and performance.
1. Number
The Number data type in JavaScript includes both integers and floating-point
numbers. Special values like Infinity, -Infinity, and NaN represent infinite values
and computational errors, respectively.
let n1 = 2;
[Link](n1)

let n2 = 1.3;
[Link](n2)

let n3 = Infinity;
[Link](n3)

let n4 = 'something here too' / 2;


[Link](n4)

Output
2
1.3
Infinity

PDVP collage Tasgaon Mr. J.H. Lawand


6

NaN

2. String
A String in JavaScript is a series of characters that are surrounded by quotes.
There are three types of quotes in JavaScript, which are.
let s1 = "Hello There";
[Link](s1);

let s2 = 'Single quotes work fine';


[Link](s2);

let s3 = `can embed ${s1}`;


[Link](s3);

Output
Hello There
Single quotes work fine
can embed Hello There
There's no difference between 'single' and "double" quotes in JavaScript.
Backticks provide extra functionality as with their help of them we can embed
variables inside them.
3. Boolean
The boolean type has only two values i.e. true and false.
let b1 = true;
[Link](b1);

let b2 = false;
[Link](b2);

Output
true
false

4. Null
The special null value does not belong to any of the default data types. It forms a
separate type of its own which contains only the null value.
let age = null;
[Link](age)

Output
null
The 'null' data type defines a special value that represents nothing, or empty
value.

PDVP collage Tasgaon Mr. J.H. Lawand


7

5. Undefined
A variable that has been declared but not initialized with a value is automatically
assigned the undefined value. It means the variable exists, but it has no value
assigned to it.
let a;
[Link](a);

Output
undefined

6. Symbol (Introduced in ES6)


Symbols, introduced in ES6, are unique and immutable primitive values used as
identifiers for object properties. They help create unique keys in objects,
preventing conflicts with other properties.
let s1 = Symbol("Geeks");
let s2 = Symbol("Geeks");
[Link](s1 == s2);

Output
false

7. BigInt (Introduced in ES2020)


BigInt is a built-in object that provides a way to represent whole numbers greater
than 253. The largest number that JavaScript can reliably represent with the
Number primitive is 253, which is represented by the MAX_SAFE_INTEGER
constant.
let b = BigInt("0b1010101001010101001111111111111111");
[Link](b);
Non-Primitive Data Types
The data types that are derived from primitive data types are known as non-
primitive data types. It is also known as derived data types or reference data
types.
1. Object
JavaScript objects are key-value pairs used to store data, created with {} or the
new keyword. They are fundamental as nearly everything in JavaScript is an
object.
let gfg = {
type: "Company",
location: "Noida"
}
[Link]([Link])

Output
Company

PDVP collage Tasgaon Mr. J.H. Lawand


8

2. Arrays
An Array is a special kind of object used to store an ordered collection of values,
which can be of any data type.
let a1 = [1, 2, 3, 4, 5];
[Link](a1);

let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];


[Link](a2);

Output
[ 1, 2, 3, 4, 5 ]
[ 1, 'two', { name: 'Object' }, [ 3, 4, 5 ] ]

3. Function
A function in JavaScript is a block of reusable code designed to perform a
specific task when called.
// Defining a function to greet a user
function greet(name) { return "Hello, " + name + "!"; }
// Calling the function
[Link](greet("Ajay"));

Output
Hello, Ajay!

4. Date Object
The Date object in JavaScript is used to work with dates and times, allowing for
date creation, manipulation, and formatting.
// Creating a new Date object for the
// current date and time
let currentDate = new Date();

// Displaying the current date and time


[Link](currentDate);

Output
2025-03-08T06:23:33.202Z

5. Regular Expression
A RegExp (Regular Expression) in JavaScript is an object used to define search
patterns for matching text in strings.
// Creating a regular expression to match the word "hello"
let pattern = /hello/;

// Testing the pattern against a string


// Returns false because "hello" is not present

PDVP collage Tasgaon Mr. J.H. Lawand


9

let result = [Link]("Hello, world!");

[Link](result);

Output
false

JavaScript - Operators
In JavaScript, an operator is a symbol that performs an operation on one or more operands,
such as variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal
to 9. Here 4 and 5 are called operands, and + is called the operator.

JavaScript supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Bitwise Operators
 Assignment Operators
 Miscellaneous Operators

JavaScript Arithmetic Operators


The JavaScript arithmetic operators are used to perform mathematical calculations such as
addition, multiplication, subtraction, division, etc. on numbers. JavaScript supports the
following arithmetic operators −

Assume variable x holds 10 and variable y holds 20, then −

Operator Description Example

+ (Addition) Adds two operands. x + y will give 30.

Subtracts the second operand from the


- (Subtraction) x - y will give -10.
first.

* (Multiplication) Multiplies both operands. x * y will give 200.

Divides the numerator by the


/ (Division) y / x will give 2.
denominator.

Outputs the remainder of an integer


% (Modulus) y % x will give 0
division.

PDVP collage Tasgaon Mr. J.H. Lawand


10

++ (Increment) Increases an integer value by one. x++ will give 11.

-- (Decrement) Decreases an integer value by one. x-- will give 9.

JavaScript Comparison Operators


The JavaScript comparison operators compare two values and returns a boolean result
(true or false). JavaScript supports the following comparison operators −

Assume variable x holds 10 and variable y holds 20, then −

Operator Description Example

Checks if the value of two operands is


== (Equal) equal or not. If yes, then the condition (x == y) is not true.
becomes true.

Checks if the value of two operands is


!= (Not Equal) equal or not. If the values are not equal, (x != y) is true.
then the condition becomes true.

It checks whether the value and data type of


=== (Strict equality) the variable is equal or not. If yes, then the (x === y) is not true.
condition becomes true.

It checks whether the value and data type of


!== (Strict inequality) the variable is equal or not. If the values are (x !== y) is true.
not equal, then the condition becomes true.

Checks if the value of the left operand is


> (Greater than) greater than the value of the right operand. (x > y) is not true.
If yes, then the condition becomes true.

Checks if the value of the left operand is


< (Less than) less than the value of the right operand. If (x < y) is true.
yes, then the condition becomes true.

Checks if the value of the left operand is


greater than or equal to the value of the
>= (Greater than or Equal to) (x >= y) is not true.
right operand. If yes, then the condition
becomes true.

PDVP collage Tasgaon Mr. J.H. Lawand


11

Checks if the value of the left operand is


less than or equal to the value of the right
<= (Less than or Equal to) (x <= y) is true.
operand. If yes, then the condition becomes
true.

JavaScript Logical Operators


The logical operators are generally used to perform logical operations on boolean values. But
logical operators can be applied to values of any types not only boolean.

JavaScript supports the following logical operators −

Assume that the value of x is 10 and y is 0.

Operator Description Example

If both the operands are non-zero, then the


&& (Logical AND) (x && y) is false
condition becomes true.

If any of the two operands are non-zero, then the


|| (Logical OR) (x || y) is true.
condition becomes true.

Reverses the logical state of its operand. If a


! (Logical NOT) condition is true, then the Logical NOT operator !x is false.
will make it false.

JavaScript Bitwise Operators


The JavaScript bitwise operators are used to perform bit-level operations on integers.
JavaScript supports the following seven types of bitwise operators −

Assume variable x holds 2 and variable y holds 3, then −

Operator Description Example

PDVP collage Tasgaon Mr. J.H. Lawand


12

It performs a Boolean AND operation on each


& (Bitwise AND) (x & y) is 2.
bit of its integer arguments.

It performs a Boolean OR operation on each bit


| (Bitwise OR) (x | y) is 3.
of its integer arguments.

It performs a Boolean exclusive OR operation


on each bit of its integer arguments. Exclusive
^ (Bitwise XOR) (x ^ y) is 1.
OR means that either operand one is true or
operand two is true, but not both.

It is a unary operator and operates by reversing


~ (Bitwise Not) (~y) is -4.
all the bits in the operand.

It moves all the bits in its first operand to the


left by the number of places specified in the
second operand. New bits are filled with zeros.
<< (Left Shift) Shifting a value left by one position is (x << 1) is 4.
equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and
so on.

Binary Right Shift Operator. The left operands


>> (Right Shift) value is moved right by the number of bits (x >> 1) is 1.
specified by the right operand.

This operator is just like the >> operator, except


>>> (Right shift with Zero) that the bits shifted in on the left are always (x >>> 1) is 1.
zero.

JavaScript Assignment Operators


In JavaScript, an assignment operator is used to assign a value to a variable. JavaScript
supports the following assignment operators −

Operator Description Example

z=x
= (Simple &plus; y
Assigns values from the right side operand to the left side operand will
Assignment)
assign the
value of x

PDVP collage Tasgaon Mr. J.H. Lawand


13

&plus; y
into z

z &plus;=
&plus;= (Add x is
It adds the right operand to the left operand and assigns the result to
and equivalent
the left operand.
Assignment) to z = z
&plus; x

z -= x is
= (Subtract and It subtracts the right operand from the left operand and assigns the equivalent
Assignment) result to the left operand. to z = z -
x

z &ast;=
&ast;=(Multiply x is
It multiplies the right operand with the left operand and assigns the
and equivalent
result to the left operand.
Assignment) to z = z
&ast; x

z /= x is
/= (Divide and It divides the left operand with the right operand and assigns the equivalent
Assignment) result to the left operand. to z = z /
x

z %= x is
%= (Modules
It takes modulus using two operands and assigns the result to the left equivalent
and
operand. to z = z %
Assignment)
x

JavaScript Miscellaneous Operators


There are few other operators supported by JavaScript. These operators
are conditional operator (? :), typeof operator, delete operator, etc.

In the below table, we have given the JavaScript miscellaneous operators with its
explanation.

Operator Description

PDVP collage Tasgaon Mr. J.H. Lawand


14

If Condition is true? Then value X : Otherwise


? : (Conditional )
value Y

typeof It returns the data type of the operand.

It returns its right-hand side operand when its left-


?? (Nullish Coalescing Operator) hand side operand is null or undefined, and
otherwise returns its left-hand side operand.

delete It removes a property from an object.

It evaluates its operands (from left to right) and


, (Comma)
returns the value of the last operand.

() (Grouping) It allows to change the operator precedence.

It is used to pause and resume a generator


yield
function.

It is used to expand the iterables such as array or


(Spread)
string.

Raises the left operand to the power of the right


** (Exponentiation)
operand

Control Statements in JavaScript


JavaScript control statement is used to control the execution of a program based
on a specific condition. If the condition meets then a particular block of action will
be executed otherwise it will execute another block of action that satisfies that
particular condition.

Types of Control Statements in JavaScript


 Conditional Statement: These statements are used for decision-making, a
decision
 n is made by the conditional statement based on an expression that is passed.
Either YES or NO.
 Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement will keep
repeating itself until and unless it is satisfied.

1: If Statement
In this approach, we are using an if statement to check a specific condition, the
code block gets executed when the given condition is satisfied.
Syntax

PDVP collage Tasgaon Mr. J.H. Lawand


15

if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Now let's understand this with the help of example:
const num = 5;

if (num > 0) {
[Link]("The number is positive.");
};

Output
The number is positive.

2: Using If-Else Statement


The if-else statement will perform some action for a specific condition. If the
condition meets then a particular code of action will be executed otherwise it will
execute another code of action that satisfies that particular condition.
Syntax
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Now let's understand this with the help of example:
let num = -10;

if (num > 0)
[Link]("The number is positive.");
else
[Link]("The number is negative");

Output
The number is negative

3: Using Switch Statement


The switch case statement in JavaScript is also used for decision-making purposes.
In some cases, using the switch case statement is seen to be more convenient than
if-else statements.
Syntax
switch (expression) {
case value1:
statement1;

PDVP collage Tasgaon Mr. J.H. Lawand


16

break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Now let's understand this with the help of example:
let num = 5;

switch (num) {
case 0:
[Link]("Number is zero.");
break;
case 1:
[Link]("Nuber is one.");
break;
case 2:
[Link]("Number is two.");
break;
default:
[Link]("Number is greater than 2.");
};

Output
Number is greater than 2.

4: Using the Ternary Operator (Conditional Operator)


The conditional operator, also referred to as the ternary operator (?:), is a shortcut
for expressing conditional statements in JavaScript.
Syntax
condition ? value if true : value if false
Now let's understand this with the help of example
let num = 10;

let result = num >= 0 ? "Positive" : "Negative";

[Link](`The number is ${result}.`);

Output
The number is Positive.

PDVP collage Tasgaon Mr. J.H. Lawand


17

5: Using For loop


In this approach, we are using for loop in which the execution of a set of
instructions repeatedly until some condition evaluates and becomes false
Syntax
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
Now let's understand this with the help of example:
for (let i = 0; i <= 10; i++) {
if (i % 2 === 0) {
[Link](i);
}
};

Output
0
2
4
6
8
10

6: Using While loop


The while loop repeats a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block
}
Now let's understand this with the help if example
let i = 1;

while (i <= 5) {
[Link](i);
i++;
}
Output
1
2
3
4
5

PDVP collage Tasgaon Mr. J.H. Lawand


18

7: Using Do-While loop


The do-while loop is similar to the while loop, except that the condition is
evaluated after the execution of the loop's body. This means the code block will
execute at least once, even if the condition is false.
Syntax
do {
// code block
} while (condition);
Now let's understand this with the help of example:
let i = 1;

do {
[Link](i);
i++;
} while (i <= 5);
Output
1
2
3
4
5

Element Access in JavaScript’s


JavaScript is a powerful language that can be used to manipulate the HTML
elements on a web page. By using JavaScript, we can access the HTML elements
and modify their attributes, styles, and content. This allows us to create dynamic
and interactive web pages.
Methods to Identify the elements to manipulate: There are several methods to
identify the HTML elements that we want to manipulate using JavaScript. The
most common methods are:
 Using the element's ID: We can assign an ID to an HTML element and use
[Link]() to access it.
 Using the element's class name: We can assign a class name to an HTML
element and use [Link]() to access it.
 Using the element's tag name: We can use
[Link]() to access all elements with a particular
tag name.
Get HTML element by Id
Generally, most developers use unique ids in the whole HTML document. The
user has to add the id to the particular HTML element before accessing the
HTML element with the id. Users can use getElementById() method to access
the HTML element using the id. If any element doesn't exist with the passed id
into the getElementById method, it returns the null value.

PDVP collage Tasgaon Mr. J.H. Lawand


19

Syntax:
[Link](element_ID);
Parameter:
It takes the ID of the element which the user wants to access.
Return value:
It returns the object with the particular ID. If the element with the particular ID
isn't found, it returns the NULL value.
Example: This example demonstrates the use of the getElementsById method.
Also, it prints the inner HTML of a returned object into the console of the
browser. Users can open the console in the Chrome web browser by pressing ctrl
+ shift + I.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>

<body>
<!-- Heading element with GeeksforGeeks id-->
<h1 id="Geeksforgeeks">
GeeksforGeeks
</h1>
<p>DOM getElementById() Method</p>
<script>
// Accessing the element by getElementById method
let temp = [Link]("Geeksforgeeks");

[Link](temp);
[Link]([Link]);
</script>
</body>
</html>
Output:

Get HTML element by className


In javascript, the getElementsByClassName() method is useful to access the
HTML elements using the className. The developers can use a single
className multiple times in a particular HTML document. When users try to

PDVP collage Tasgaon Mr. J.H. Lawand


20

access an element using the className, it returns the collection of all objects that
include a particular class.
Syntax:
[Link](element_classnames);
Parameter:
It takes the multiple class names of the element which the user wants to access.
Return value:
It returns the collection of objects that have a particular class name. Users can get
every element from the collection object using the index that starts from 0.
Example 1: This example demonstrates the use of
the getElementsByClassName() method. It prints every element of the returned
collection object into the console. Users can open the console in the Chrome web
browser by pressing ctrl + shift + I.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>

<body>
<!-- Multiple html element with GeeksforGeeks class name -->
<h1 class="GeeksforGeeks">GeeksforGeeks sample 1</h1>
<h1 class="GeeksforGeeks">GeeksforGeeks sample 2</h1>
<h1 class="GeeksforGeeks">GeeksforGeeks sample 3</h1>

<p>DOM getElementsByclassName() Method</p>


<script>

// Accessing the element by getElementsByclassName method


let temp = [Link]("GeeksforGeeks");
[Link](temp[0]);
[Link](temp[1]);
[Link](temp[2]);
</script>
</body>
</html>
Output:

PDVP collage Tasgaon Mr. J.H. Lawand


21

JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser. They
can be triggered by various user interactions or by the browser itself.

<html>
<script>
function myFun() {
[Link](
"gfg").innerHTML = "GeeksforGeeks";
}
</script>
<body>
<button onclick="myFun()">Click me</button>
<p id="gfg"></p>
</body>
</html>

 The onclick attribute in the <button> calls the myFun() function when clicked.
 The myFun() function updates the <p> element with id="gfg" by setting its
innerHTML to "GeeksforGeeks".

PDVP collage Tasgaon Mr. J.H. Lawand


22

 Initially, the <p> is empty, and its content changes dynamically on button
click.

Event Types
JavaScript supports a variety of event types. Common categories include:
 Mouse Events: click, dblclick, mousemove, mouseover, mouseout
 Keyboard Events: keydown, keypress, keyup
 Form Events: submit, change, focus, blur
 Window Events: load, resize, scroll

1. onClick ()-
The onclick event in JavaScript is triggered when a user clicks on an HTML element. It is commonly
used to execute a function when a button or other clickable element is clicked.

Example: Using onclick Attribute in HTML


You can directly add the onclick attribute to an HTML element and specify the function to be
executed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Onclick Example</title>
</head>
<body>
<button onclick="showMessage()">Click me</button>

<script>
function showMessage() {
alert("Button clicked!");
}
</script>
</body>
</html>

2. onBlur()
The HTML DOM onblur event occurs when an object loses focus.
The onblur event is the opposite of the onfocus event. The onblur event is
mostly used with form validation code (e.g. when the user leaves a form field).
In HTML:
<element onblur="myScript">
<!DOCTYPE html>
<html lang="en">
<body>
Email:
<input type="email" id="email" onblur="myFunction()">
<script>

PDVP collage Tasgaon Mr. J.H. Lawand


23

function myFunction() {
alert("Focus lost");
}
</script>
</body>
</html>
In JavaScript:
[Link] = function(){myScript};
<!DOCTYPE html>
<html lang="en">
<body>
<input type="email" id="email">
<script>
[Link]("email").onblur = function () {
myFunction()
};

function myFunction() {
alert("Input field lost focus.");
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
[Link]("blur", myScript);
<!DOCTYPE html>
<html lang="en">
<body>
<input type="email" id="email">
<script>
[Link](
"email").addEventListener("blur", myFunction);

function myFunction() {
alert("Input field lost focus.");
}
</script>
</body>
</html>

3. onFocus
The onfocus event in JavaScript is triggered when an element gains focus — typically when a
user clicks into an input field, tabs into it, or focuses it programmatically.
It’s commonly used with form elements like <input>, <textarea>, <select>, and <button>.

Key Points
 Does not bubble: Unlike focusin, the focus/onfocus event does not bubble up the DOM.

PDVP collage Tasgaon Mr. J.H. Lawand


24

 Can be attached inline in HTML or via JavaScript event listeners.


 Often paired with onblur (which fires when the element loses focus).

Usage in HTML
You can use the onfocus attribute directly within an HTML element to specify the script to be executed
when the element gains focus. Here is an example:
<input type="text" onfocus="myFunction()">

In this example, the myFunction function will be called when the input field receives focus.

Usage in JavaScript
In JavaScript, you can assign a function to the onfocus property of an element or use
the addEventListener method to attach an event handler. Here are examples of both approaches:
// Using the onfocus property
[Link]("myInput").onfocus = function() {
myFunction();
};

// Using addEventListener
[Link]("myInput").addEventListener("focus", myFunction);

In both cases, the myFunction function will be executed when the input field with the
ID myInput receives focus

4. onKeyPress()
Whenever a key is pressed or released, there are certain events that are triggered.
Each of these events has a different meaning and can be used for implementing
certain functionalities depending on the current state and the key that is being
used.
These events that are triggered when a key is pressed are in the following order:
 keydown Event: This event occurs when the user has pressed down the key.
It will occur even if the key pressed does not produce a character value.
 keypress Event: This event occurs when the user presses a key that produces
a character value. These include keys such as the alphabetic, numeric, and
punctuation keys. Modifier keys such as 'Shift', 'CapsLock', 'Ctrl' etc. do not
produce a character, therefore they have no 'keypress' event attached to them.
 keyup Event: This event occurs when the user has released the key. It will
occur even if the key released does not produce a character value.
Note that different browsers may have different implementations of the above
events. The onKeyDown, onKeyPress, and onKeyUp events can be used to
detect these events respectively.
Example: The below example shows different events that get triggered when a
key is pressed in their respective order.

PDVP collage Tasgaon Mr. J.H. Lawand


25

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>

<body>

<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>

<p>
<b>onKeyPress Vs. onKeyUp
and onKeyDown Events</b>
</p>

<input type="text" id="field" placeholder="Type here">


<p id="status"></p>

<script>
let key_pressed =
[Link]('field');

key_pressed
.addEventListener("keydown", onKeyDown);
key_pressed
.addEventListener("keypress", onKeyPress);
key_pressed
.addEventListener("keyup", onKeyUp);

function onKeyDown(event) {
[Link]("status")
.innerHTML = 'keydown: '
+ [Link] + '<br>'
}
function onKeyPress(event) {
[Link]("status")
.innerHTML += 'keypress: '
+ [Link] + '<br>'
}
function onKeyUp(event) {
[Link]("status")
.innerHTML += 'keyup: '

PDVP collage Tasgaon Mr. J.H. Lawand


26

+ [Link] + '<br>'
}
</script>
</body>
</body>

</html>

JavaScript Dialogue Boxes


A dialogue box in JavaScript is a pop-up message that appears on the screen
when the user interacts with the webpage. These boxes help provide feedback,
ask for confirmation, or collect data from the user.
JavaScript offers three types of dialogue boxes that serve different purposes:
 Alert
 Prompt
 Confirm

1. Alert Box
The alert box is the simplest type of dialogue box. It is used to display a message
to the user, typically for informational purposes. It contains only a message and an
OK button that the user can click to close the box.
How It Works
 When the alert() function is called, the browser will display a pop-up box with
your specified message.
 The user must click the OK button to close the box and continue interacting
with the webpage.
<html>
<head></head>
<body>
<script type="text/javascript">
function Warning() {
alert("Warning danger you have not filled everything");
[Link]("Warning danger you have not filled everything");

}
</script>
<p>Click the button to check the Alert Box functionality</p>
<form>
<input type="button" value="Click Me" onclick="Warning();" />
</form>
</body>
</html>
Output:

PDVP collage Tasgaon Mr. J.H. Lawand


27

Alert Box in JavaScript


In this example
 Button: There’s a button labeled "Click Me."
 Function: When clicked, the button calls the Warning() function.
 Alert: The function shows an alert with a warning message.
 Console Log: The same warning message is printed in the browser's console.

2. Confirm box
The confirm box is slightly more advanced than the alert box. It asks the user for
confirmation with two buttons: OK and Cancel. Based on the user's choice, we can
take specific actions.
How It Works
 When the confirm() function is called, the browser displays a pop-up box with
the message and two options: OK and Cancel.
 If the user clicks OK, the function returns true.
 If the user clicks Cancel, the function returns false.
 Use the returned value (true or false) to perform different actions based on the
user's choice. <script type="text/javascript">
function Confirmation() {
var Val = confirm("Do you want to continue ?");
if (Val == true) {
[Link](" CONTINUED!");
return true;
} else {
[Link]("NOT CONTINUED!");
return false;
}
}
</script>

<p>Click the button to check the Confirm Box functionality</p>


<form>
<input type="button" value="Click Me" onclick="Confirmation();" />
</form>
Output:

PDVP collage Tasgaon Mr. J.H. Lawand


28

Confirm Box in JavaScript


In this example
 Button: There’s a "Click Me" button.
 Function: Clicking the button calls the Confirmation() function.
 Confirm Box: A pop-up asks, "Do you want to continue?"
 User Decision: If OK is clicked, it logs "CONTINUED!" in the console. If
Cancel is clicked, it logs "NOT CONTINUED!".
 Returns: The function returns true if continued, false if not.

3. Prompt Box
The prompt box allows you to ask the user for input. It provides a text field where
the user can enter data and a OK and Cancel button. You can use this to collect
information from the user, like their name, age, or email.
How It Works
 When the prompt() function is called, a pop-up appears with a text field, and
the user is asked to input something.
 If user can click OK, the text they entered is returned as a string. If user click
Cancel the function returns null.
 Use the value returned by prompt() for any further logic, such as displaying it
on the webpage or processing it in other ways. <script type="text/javascript">
function Value(){
var Val = prompt("Enter your name : ", "Please enter your name");
[Link]("You entered : " + Val);
}

</script>

<p>Click the button to check the Prompt Box functionality</p>


<form>
<input type="button" value="Click Me" onclick="Value();" />
</form>
Output:

Prompt box in JavaScript

PDVP collage Tasgaon Mr. J.H. Lawand


29

In this example
 Button: There’s a "Click Me" button.
 Function: Clicking the button calls the Value() function.
 Prompt Box: A pop-up asks the user to "Enter your name."
 User Input: Whatever the user types is saved in the Val variable.
 Console Log: The entered name is logged in the console with the message
"You entered: [name]."

Comparison of Dialogue Boxes


Here is the comparison of dialogue boxes:
Alert Box Confirm Box Prompt Box

Displays
Asks for user confirmation Collects user input
information

Return value is Return value is true (OK) or Return value is User's input
none false (Cancel) (string) or null

Show simple
Ask for confirmation (Yes/No) Collect user input (text)
messages

Button: Ok Button : OK, Cancel Button: OK, Cancel

PDVP collage Tasgaon Mr. J.H. Lawand

You might also like