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

Javascript Class.docx

The document provides an introduction to JavaScript, covering its definition, common uses, and installation steps for running JavaScript programs. It explains basic programming concepts such as variable declaration with var, let, and const, as well as operators, conditional statements, and loops. Additionally, it includes examples and exercises to reinforce understanding of JavaScript syntax and functionality.
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)
33 views

Javascript Class.docx

The document provides an introduction to JavaScript, covering its definition, common uses, and installation steps for running JavaScript programs. It explains basic programming concepts such as variable declaration with var, let, and const, as well as operators, conditional statements, and loops. Additionally, it includes examples and exercises to reinforce understanding of JavaScript syntax and functionality.
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
You are on page 1/ 89

1.

Introduction to JavaScript
Definition
JavaScript is a versatile programming language primarily used to add
interactivity to websites. It runs in the browser, interacts with HTML and
CSS, and is used in both frontend and backend development. It is a
lightweight, interpreted, or just-in-time compiled language that is one of
the core technologies of the World Wide Web, alongside HTML and CSS.

Common Uses of JavaScript:


1.​ Web Development: Creating interactive user interfaces, form
validations, animations, etc.
2.​ Backend Development: With Node.js, JavaScript can also be used to
build server-side applications.
3.​ Game Development: For building lightweight browser games.

4.​ Mobile App Development: Frameworks like React Native enable


mobile app development using JavaScript.
5.​ Data Visualization: Libraries like D3.js and Chart.js make it easier to
visualize data.

Examples:
// Simple greeting in JavaScript
console.log("Hello, JavaScript World!");

// Adding interactivity to a webpage


let button = document.createElement('button');
button.textContent = "Click Me";
button.onclick = () => alert("Button clicked!");
document.body.appendChild(button);

2. Install VS Code and Run First Program


Steps:

1.​ Download and install Visual Studio Code from


https://code.visualstudio.com/.
2.​ Install Node.js to run JavaScript outside the browser.
3.​ Create a new file with a .js extension, e.g., script.js.
4.​ Write the following code in the file:

console.log("Your first JavaScript program!");

5.​ Open the terminal, navigate to the file location, and run:

node script.js

3. Basics of Programming in JavaScript

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

Types of JavaScript Comments


There are two types of comments in JavaScript.

1.​ Single-line Comment


2.​ Multi-line Comment

JavaScript Single line Comment


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

Let’s see the example of single-line comment i.e. added before the statement.

​ <script>
​ // It is single line comment
​ document.write("hello javascript");
​ </script>

JavaScript Multi line Comment


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

It is represented by forward slash with asterisk then asterisk with forward


slash. For example:
​ <script>
​ /* It is multi line comment.
​ It will not be displayed */
​ document.write("example of javascript multiline comment");
​ </script>

2. Declare Variables Using var

Definition: var is a keyword used to declare variables in JavaScript. It has


function scope and can be re-declared and updated.

Example Code:

var age = 25;

console.log("Age:", age);

var age = 30; // Re-declaration

console.log("Updated Age:", age);

Output:

Age: 25

Updated Age: 30

Exercises:

1.​ Declare a variable city using var and assign it the value "Delhi". Then
update it to "Mumbai".
2.​ Declare a variable price and assign it any number. Update it to a new
value.

Answers:

// Exercise 1

var city = "Delhi";

console.log("City:", city);

city = "Mumbai";

console.log("Updated City:", city);


// Exercise 2

var price = 100;

console.log("Price:", price);

price = 150;

console.log("Updated Price:", price);

Output:

City: Delhi

Updated City: Mumbai

Price: 100

Updated Price: 150

3. More About Variables

Definition: Variables in JavaScript can hold values like numbers, strings,


objects, and booleans. You can assign different types to the same variable.

Example Code:

var data = "Kartik";

console.log("String:", data);

data = 25; // Assigning a number

console.log("Number:", data);

data = true; // Assigning a boolean

console.log("Boolean:", data);

Output:

String: Kartik

Number: 25
Boolean: true

Exercises:

1.​ Create a variable status and assign it the value false. Change it to true.
2.​ Assign a number to a variable marks. Later, change its value to a
string.

Answers:

// Exercise 1

var status = false;

console.log("Status:", status);

status = true;

console.log("Updated Status:", status);

// Exercise 2

var marks = 85;

console.log("Marks:", marks);

marks = "Excellent";

console.log("Updated Marks:", marks);

Output:

Status: false

Updated Status: true

Marks: 85

Updated Marks: Excellent

4. let

Definition: let is used to declare variables with block scope. Unlike var, it
cannot be re-declared in the same scope.
Example Code:

let name = "Kartik";

console.log("Name:", name);

name = "Sharma"; // Can update the value

console.log("Updated Name:", name);

// let name = "New"; // This will throw an error

Output:

yaml

Name: Kartik

Updated Name: Sharma

Exercises:

1.​ Declare a variable country using let and assign it the value "India". Try
updating it.
2.​ Use let in a block (e.g., an if statement) and try accessing it outside
the block.

Answers:

javascript

// Exercise 1

let country = "India";

console.log("Country:", country);

country = "USA";

console.log("Updated Country:", country);


// Exercise 2

if (true) {

let greeting = "Hello";

console.log("Inside Block:", greeting);

// console.log("Outside Block:", greeting); // Error: greeting is not defined

Output:

yaml

Country: India

Updated Country: USA

Inside Block: Hello

5. const

Definition: const declares variables that cannot be updated or re-declared. It


must be initialized during declaration.

Example Code:

javascript

const pi = 3.14;

console.log("Value of pi:", pi);

// pi = 3.1415; // This will throw an error

Output:

lua

Value of pi: 3.14


Exercises:

1.​ Declare a const variable speedOfLight with a value of 299792458. Try


re-assigning it.
2.​ Use const to declare an array. Modify the array content but not the
reference.

Answers:

javascript

// Exercise 1

const speedOfLight = 299792458;

console.log("Speed of Light:", speedOfLight);

// speedOfLight = 300000000; // Error

// Exercise 2

const colors = ["red", "green", "blue"];

console.log("Colors:", colors);

colors.push("yellow");

console.log("Updated Colors:", colors);

Output:

less

Speed of Light: 299792458

Colors: ["red", "green", "blue"]

Updated Colors: ["red", "green", "blue", "yellow"]


JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:

​ var sum = 10 + 20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1.​ Arithmetic Operators


2.​ Comparison (Relational) Operators
3.​ Logical Operators
4.​ Assignment Operators
5.​ Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic
operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200


/ Division 20/10 = 2

++ Increment var a=10; a++; Now a =


11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:

Operator Description Example

=== Identical (equal and of 10==20 = false


same type)

!= Not equal to 10!=20 = true

> Greater than 20>10 = true

>= Greater than or equal 20>=10 = true


to

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


JavaScript Logical Operators
The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) =


false

|| Logical OR (10==20 || 20==33) =


false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a


= 30

-= Subtract and assign var a=20; a-=10; Now a


= 10
*= Multiply and assign var a=10; a*=20; Now a
= 200

/= Divide and assign var a=10; a/=2; Now a =


5

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value


based on the condition. It is like
if-else.

, Comma Operator allows multiple


expressions to be evaluated as
single statement.

new creates an instance (object)

typeof checks the type of object.

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

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

​ if(expression){
​ //content to be evaluated
​ }

Flowchart of JavaScript If statement


Let’s see the simple example of if statement in javascript.

​ <script>
​ var a=20;
​ if(a>10){
​ document.write("value of a is greater than 10");
​ }
​ </script>

Output of the above example


value of a is greater than 10

JavaScript If...else Statement


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

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

​ <script>
​ var a=20;
​ if(a%2==0){
​ document.write("a is even number");
​ }
​ else{
​ document.write("a is odd number");
​ }
​ </script>
Output of the above example
a is even number

JavaScript If...else if statement


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

​ if(expression1){
​ //content to be evaluated if expression1 is true
​ }
​ else if(expression2){
​ //content to be evaluated if expression2 is true
​ }
​ else if(expression3){
​ //content to be evaluated if expression3 is true
​ }
​ else{
​ //content to be evaluated if no expression is true
​ }

​ <script>
​ var a=20;
​ if(a==10){
​ document.write("a is equal to 10");
​ }
​ else if(a==15){
​ document.write("a is equal to 15");
​ }
​ else if(a==20){
​ document.write("a is equal to 20");
​ }
​ else{
​ document.write("a is not equal to 10, 15 or 20");
​ }
​ </script>

Output of the above example


a is equal to 20

JavaScript Switch
switch statement evaluates the condition to match the condition with the
series of cases and if the condition is matched then it executes the statement.
If the condition is not matched with any case then the default condition will
be executed.

switch (expression) {

case value1:

// Code to execute if expression === value1

break;

case value2:

// Code to execute if expression === value2

break;

default:

// Code to execute if none of the cases match

}
Break Statement

After the execution of the code block in a program break statement helps us
so it terminates the switch statement and prevents the execution from falling
through to subsequent cases.

Example of switch case statement:

let day = 3;

switch (day) {

case 1:

console.log("Monday");

break;

case 2:

console.log("Tuesday");

break;

case 3:

console.log("Wednesday");

break;

case 4:

console.log("Thursday");

break;

default:

console.log("Invalid day");

}
Output:

Wednesday (because day = 3 matches case 3)

Example 2: Switch Case Without Break (Fall-through)

let fruit = "apple";

switch (fruit) {

case "apple":

console.log("Apples are red.");

case "banana":

console.log("Bananas are yellow.");

case "grapes":

console.log("Grapes are purple.");

break;

default:

console.log("Unknown fruit.");

Output:

Apples are red.

Bananas are yellow.

Grapes are purple.


JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It is mostly used in array. It is also called iterative
statements.

Advantages of using Loop:


1.​ It perform repetitive task with less number of codes.

There are four types of loops in JavaScript.

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. It executes a block of code
until a specified condition is true.

The syntax of for loop is given below

​ for (initialization; condition; increment)


​ {
​ code to be executed
​ }

In the above syntax:

○​ Initialize: This is an expression that starts the loop.


○​ condition: This is a Boolean expression that specifies whether the
loop should execute a loop or not.
○​ Increment/Decrement: Executes the iterate (i.e. increment and
decrement) after each iteration of the for loop statement.
Let's see the simple example of for loop in javascript.

​ // for loop to print numbers from 1 to 5


​ for (let i = 1; i <= 5; i++) {
​ console.log(i);
​ }

Output:

1️⃣ Question 1: Even Numbers from 1 to 10

🔹 Code:
for (let i = 2; i <= 10; i += 2) {

console.log(i);

📌 Output:
2

6
8

10

Loop Execution (Step by Step)

Iterat i ki Condition (i console.lo i += 2 (Next i


ion value <= 10) g(i) value)

1st 2 ✅ (True) Prints 2 i = 2 + 2 = 4

2nd 4 ✅ (True) Prints 4 i = 4 + 2 = 6

3rd 6 ✅ (True) Prints 6 i = 6 + 2 = 8

4th 8 ✅ (True) Prints 8 i = 8 + 2 = 10

5th 10 ✅ (True) Prints 10 i = 10 + 2 = 12

6th 12 ❌ (False) Loop stops —

Final Output:

10
2️⃣ Question 2: Sum of First 5 Numbers

let sum = 0;

for (let i = 1; i <= 5; i++) {

sum = sum + i;

console.log("Sum:", sum);

📌 Output:
Sum: 15

(kyunki 1+2+3+4+5 = 15)

🔹 Loop Execution Flow:


1.​ i = 1 → sum = 1
2.​ i = 2 → sum = 3
3.​ i = 3 → sum = 6
4.​ i = 4 → sum = 10
5.​ i = 5 → sum = 15
6.​ i = 6 → Condition i <= 5 false ho gayi, loop stop ho gaya.
3️⃣ Question 3: Reverse Counting from 5 to 1

🔹 Code:
for (let i = 5; i >= 1; i--) {

console.log(i);

📌 Output:
5

1
🔹 Loop Execution Step-by-Step:
Iteration i ki Value Condition Output i-- (Next Value)
(i >= 1)

1st 5 ✅ (true) 5 4

2nd 4 ✅ (true) 4 3

3rd 3 ✅ (true) 3 2

4th 2 ✅ (true) 2 1

5th 1 ✅ (true) 1 0

6th 0 ❌ (false) - -

Jab i = 0 hota hai, toh condition i >= 1 false ho jati hai aur
loop ruk jata hai.

4️⃣ Question 4: Multiplication Table of 3

🔹 Code:
let num = 3;

for (let i = 1; i <= 10; i++) {


console.log(`${num} x ${i} = ${num * i}`);

📌 Output:
3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

3 x 5 = 15

3 x 6 = 18

3 x 7 = 21

3 x 8 = 24

3 x 9 = 27

3 x 10 = 30

Loop Execution Step-by-Step

Iteration i Value Condition Multiplication Output


Check

1st 1 ✅ True 3 x 1 = 3 3 x 1 = 3

2nd 2 ✅ True 3 x 2 = 6 3 x 2 = 6
3rd 3 ✅ True 3 x 3 = 9 3 x 3 = 9

... ... ... ... ...

10th 10 ✅ True 3 x 10 = 30 3 x 10 = 30

11th 11 ❌ False Loop stops

Final Output in Console

3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

3 x 5 = 15

3 x 6 = 18

3 x 7 = 21

3 x 8 = 24

3 x 9 = 27

3 x 10 = 30

5️⃣ Question 5: Print an Array using a Loop

🔹 Code:
let fruits = ["Apple", "Banana", "Mango", "Grapes"];

for (let i = 0; i < fruits.length; i++) {

console.log(fruits[i]);

📌 Output:
Apple

Banana

Mango

Grapes

2) JavaScript while loop


Loops can execute a block of code as long as a specified condition is true.

1️⃣ while Loop Kya Hota Hai?

Jab humein ek kaam baar-baar repeat karna ho jab tak koi condition true
ho, tab hum while loop ka use karte hain.

2️⃣ while Loop Ka Basic Syntax

while (condition) {

// Yeh code tab tak chalega jab tak condition true hai

}
👉 condition ko har baar check kiya jaata hai.​
👉 Agar condition true hai, toh loop chalega.​
👉 Jaise hi condition false ho gayi, loop ruk jayega.

Example to print number upto 5

let count = 1; // Shuru ka number

while (count <= 5) { // Jab tak count 5 se chhota ya barabar


hai, loop chalega

console.log("Number is:", count);

count++; // Har baar count ka value 1 se badha dena

Output:

Number is: 1

Number is: 2

Number is: 3

Number is: 4

Number is: 5

3) JavaScript do while loop


The do while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.
do...while loop ek baar toh chalta hi hai, chahe condition false ho!​
Agar humein kam se kam ek baar loop execute karna ho, toh do...while
loop best hai.

1️⃣ do...while Loop Ka Basic Syntax


do {

// Yeh code ek baar toh chalega hi

} while (condition);

●​ Pehle code execute hota hai, phir condition check hoti hai.
●​ Agar condition true hai, toh loop phir se chalega.
●​ Agar condition false hai, toh ek hi baar chalega aur ruk jayega.

2️⃣ do...while Loop Example

Print 1 se 5 .

✅ Using do...while Loop


let count = 1;

do {

console.log("Number:", count);

count++;

} while (count <= 5);


Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

4) JavaScript for in loop

for...in loop object properties ya array indexes ko iterate karne ke liye use
hota hai. Yeh loop keys (properties) par focus karta hai, values par nahi.

1️⃣ for...in Loop Syntax


javascript

CopyEdit

for (let key in object) {

// Code to execute for each property

●​ key → Object ki har ek property ka naam (key) milega.


●​ object → Jis object ke properties ko loop through karna hai.
2️⃣ Example - Loop Through an Object

Maan lo humein ek student ka data iterate karna hai.

javascript

CopyEdit

let student = {

name: "Kartik",

age: 25,

Place: "SIKAR"

};

for (let key in student) {

console.log(key + ": " + student[key]);

Output:

name: Kartik

age: 25

place: SIKAR

👉 Yeh loop object ke har ek property (key) ko access karta hai aur uski
value print karta hai.
3️⃣ for...in Loop with Arrays

Jab for...in loop ko array ke saath use karte hain, toh yeh indexes ko
return karta hai, values ko nahi.

✅ Example - Loop Through an Array


let colors = ["Red", "Green", "Blue"];

for (let index in colors) {

console.log(index + ": " + colors[index]);

Output:

0: Red

1: Green

2: Blue

👉 Yeh loop sirf index return karta hai, actual value nahi.​
👉 Agar sirf values chahiye toh for...of loop better hai.

✅ Example - for...of with Arrays


let colors = ["Red", "Green", "Blue"];
for (let color of colors) {

console.log(color);

Output:

Red

Green

Blue

JavaScript Functions
A function is a block of code that performs a specific task. Instead of writing
the same code multiple times, we write a function once and use it whenever
needed.

How to declare a Function:


To declare a function we have to use the reserved keyword "function", followed
by its name, and a set of arguments.

JavaScript Function Syntax


The syntax of declaring function is given below.

​ function functionName([arg1, arg2, ...argN]){


​ //code to be executed
​ }

In the above syntax, function is a reserved keyword and "functionName" is a


name given to the function. JavaScript Functions can have 0 or more
arguments.
Creating a Simple Function

Example: A function that says "Hello!"

function sayHello() {

console.log("Hello, students!");

This function, when called, will print "Hello, students!"

Step 4: Calling (Using) a Function

A function doesn’t run automatically. We need to call it.

sayHello(); // Output: Hello, students!

Whenever we call sayHello(), it executes the code inside it.

Function with Parameters (Inputs)

A function can take inputs and use them inside the code.

function greet(name) {

console.log("Hello, " + name + "!");

greet("Amit"); // Output: Hello, Amit!

greet("Neha"); // Output: Hello, Neha!


Function with Return Value (Output)

A function can also return a result instead of just printing it.

function add(a, b) {

return a + b;

console.log(add(5, 3)); // Output: 8

Function with Default Parameters

If a value is not given, a default value is used.

function greet(name = "Guest") {

return "Hello, " + name + "!";

console.log(greet()); // Output: Hello, Guest!

console.log(greet("Ravi")); // Output: Hello, Ravi!

Function Expressions (Another Way to Create Functions)

Instead of using function, we can store a function inside a variable.

const multiply = function(x, y) {

return x * y;

};
console.log(multiply(4, 2));

// Output: 8

Arrow Functions (Modern Shortcut)

Arrow functions are a shorter way to write functions in


JavaScript using the => (fat arrow) syntax. They were introduced
in ES6.

Syntax

const functionName = (parameters) => expression;

With multiple parameters:

const add = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

With a single parameter (no parentheses needed):

const square = x => x * x;

console.log(square(6)); // Output: 36

Without parameters:
const greet = () => "Hello!";

console.log(greet()); // Output: Hello!

Returning an Object in an Arrow Function

const getUser = () => ({ name: "Kartik", age: 25 });

console.log(getUser());

// Output: { name: "Kartik", age: 25 }

Find the Length of Each Word in an Array (using map function )

const words = ["Hello", "JavaScript", "Arrow"];

const lengths = words.map(word => word.length);

console.log(lengths);

// Output: [5, 10, 5]

const numbers = [1, 2, 3, 4];

const doubled = numbers.map(num => num * 2);

console.log(doubled);

// Output: [2, 4, 6, 8]

Convert Array of Strings to Uppercase

javascript
CopyEdit

Convert Array of Strings to Uppercase

const words = ["hello", "world"];

const uppercaseWords = words.map(word => word.toUpperCase());

console.log(uppercaseWords);

// Output: ["HELLO", "WORLD"]

Calling One Function from Another

function square(num) {

return num * num;

function sumOfSquares(a, b) {

return square(a) + square(b);

console.log(sumOfSquares(3, 4)); // Output: 25


Write a function that gives a snack based on a number.

function getSnack(snackNumber) {

if (snackNumber === 1) return "Chips";

if (snackNumber === 2) return "Chocolate";

return "Invalid Choice";

console.log(getSnack(1)); // Output: Chips

console.log(getSnack(3)); // Output: Invalid Choice

Advantage of JavaScript function

Functions are useful in organizing the different parts of a script into the
several tasks that must be completed. There are mainly two advantages of
JavaScript functions.

1.​ Code reusability: We can call a function several times in a script to perform
their tasks so it saves coding.
2.​ Less coding: It makes our program compact. We don't need to write many
lines of code each time to perform a common task.

Rules for naming functions:

○​ It must be start with alphabetical character (A-Z) or an underscore


symbol.
○​ It cannot contain spaces.
○​ It cannot be use as a reserve words.

1. Function: Multiply Three Numbers

function multiplyNumbers(a, b, c) {

return a * b * c;

console.log(multiplyNumbers(2, 3, 4)); // Output: 24

console.log(multiplyNumbers(1, 5, 6)); // Output: 30

console.log(multiplyNumbers(0, 4, 7)); // Output: 0

Arrow Function: Find Square of a Number

const square = (num) => num * num;

console.log(square(5)); // Output: 25

console.log(square(3)); // Output: 9

console.log(square(7)); // Output: 49

Function to Find the Largest of Two Numbers


function findLargest(a, b) {

return a > b ? a : b;

console.log(findLargest(10, 20)); // Output: 20

console.log(findLargest(5, 3)); // Output: 5

console.log(findLargest(8, 8)); // Output: 8


Function to Check if a Number is Positive, Negative, or Zero
function checkNumber(num) {

if (num > 0) return "Positive";

else if (num < 0) return "Negative";

else return "Zero";

console.log(checkNumber(5)); // Output: "Positive"

console.log(checkNumber(-3)); // Output: "Negative"

console.log(checkNumber(0)); // Output: "Zero"

Arrow Function to Find the Cube of a Number

const cube = (num) => num ** 3;

console.log(cube(2)); // Output: 8

console.log(cube(3)); // Output: 27

console.log(cube(4)); // Output: 64

Function to Check if a String Contains "JavaScript"


function containsJavaScript(str) {

return str.includes("JavaScript");

console.log(containsJavaScript("I love JavaScript!")); // Output:


true

console.log(containsJavaScript("Hello, world!")); // Output:


false
console.log(containsJavaScript("JavaScript is fun.")); // Output:
true

JavaScript Objects
An object in JavaScript is a collection of key-value pairs where keys (also called
properties) are strings, and values can be any data type (number, string,
function, array, or even another object). Objects help store structured data and
model real-world entities.

Syntax:

let objectName = {

key1: value1,

key2: value2,

key3: value3

};

●​ Each key-value pair is separated by a comma (,).


●​ Keys are strings (but quotes are optional for simple names).
●​ Values can be any valid JavaScript data type.

Example 1: Creating a Simple Object

let person = {

name: "Kartik Sharma",

age: 25,
job: "Data Analyst",

isMarried: false

};

console.log(person);

Output:

{ name: "Kartik Sharma", age: 25, job: "Data Analyst",


isMarried: false }

Accessing Object Properties

You can access properties using dot notation or bracket notation:

console.log(person.name); // Output: Kartik Sharma

console.log(person["age"]); // Output: 25

Object with Methods (Functions as Values)

let car = {

brand: "Tesla",

model: "Model S",

start: function() {
console.log("The car has started.");

};

car.start(); // Calling the method

Output:

The car has started.

we can also create Nested Objects (it means object in object )

let student = {

name: "John",

marks: {

math: 90,

science: 85

};

console.log(student.marks.math);
JavaScript Array
An array in JavaScript is a special type of object used to store multiple values in
a single variable. Arrays are ordered collections where each value is identified
by an index starting from 0.

Syntax

You can create an array using square brackets []:

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

●​ Each value in the array is called an element.


●​ Elements are separated by commas (,).
●​ Arrays can store different data types (numbers, strings, objects,
functions, etc.).

Creating an Array

let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits);

Output:

["Apple", "Banana", "Mango", "Orange"]


Accessing Array Elements

You can access elements using their index (starting from 0):

console.log(fruits[0]); // Output: Apple

console.log(fruits[2]); // Output: Mango

Modifying Array Elements


fruits[1] = "Grapes"; // Changing "Banana" to "Grapes"

console.log(fruits);

Output:

["Apple", "Grapes", "Mango", "Orange"]

JavaScript Array Methods

1. Adding and Removing Elements

1️⃣ push() - Add Element at End

Definition:
The push() method adds one or more elements to the end of an
array and returns the new length.

Syntax:

array.push(element1, element2, ...);

Example:

let fruits = ["Apple", "Banana"];

fruits.push("Mango", "Orange");

console.log(fruits); // Output: ["Apple", "Banana", "Mango",


"Orange"]

2️⃣ pop() - Remove Last Element

Definition:

The pop() method removes the last element from an array and
returns it.

Syntax:

array.pop();

Example:
let fruits = ["Apple", "Banana", "Mango"];

let removed = fruits.pop();

console.log(fruits); // Output: ["Apple", "Banana"]

console.log(removed); // Output: Mango

3️⃣ unshift() - Add Element at Beginning

Definition:

The unshift() method adds one or more elements to the beginning of an


array and returns the new length.

Syntax:

array.unshift(element1, element2, ...);

Example:

let numbers = [2, 3, 4];

numbers.unshift(1);

console.log(numbers); // Output: [1, 2, 3, 4]

4️⃣ shift() - Remove First Element

Definition:
The shift() method removes the first element from an array and
returns it.

Syntax:

array.shift();

Example:

let numbers = [1, 2, 3, 4];

let removed = numbers.shift();

console.log(numbers); // Output: [2, 3, 4]

console.log(removed); // Output: 1

Includes() - Check if Element Exists

Definition:

The includes() method checks if an array contains a specified


element, returning true or false.

Syntax:

array.includes(element);

Example:

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.includes("Mango")); // Output: true


console.log(fruits.includes("Grapes")); // Output: false

Slice() - Extract Part of Array

Definition:

The slice() method returns a shallow copy of a portion of an array


without modifying the original array.

Syntax:

array.slice(startIndex, endIndex);

Example:

let fruits = ["Apple", "Banana", "Mango", "Orange"];

let sliced = fruits.slice(1, 3);

console.log(sliced); // Output: ["Banana", "Mango"]

console.log(fruits); // Original array remains unchanged

Splice() - Add/Remove Elements

Definition:

The splice() method adds or removes elements at a specified index.

Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...);

Example:

let fruits = ["Apple", "Banana", "Mango"];

fruits.splice(1, 1, "Grapes", "Orange");

console.log(fruits); // Output: ["Apple", "Grapes", "Orange",


"Mango"]

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.

You can use different Date to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.

JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

​ Current Date and Time: <span id="txt"></span>


​ <script>
​ var today = new Date();
​ document.getElementById('txt').innerHTML=today;
​ </script>

Output:

Current Date and Time: Sun Feb 02 2025 20:49:51 GMT+0530 (India Standard Time)

JavaScript Current Time Example


Let's see the simple example to print current time of system.

​ Current Time: <span id="txt"></span>


​ <script>
​ var today=new Date();
​ var h=today.getHours();
​ var m=today.getMinutes();
​ var s=today.getSeconds();
​ document.getElementById('txt').innerHTML=h+":"+m+":"+s;
​ </script>

Current Time: 20:49:51

JavaScript Math
The JavaScript math object provides several constants and methods to
perform mathematical operation.

JavaScript Math Methods

Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given
number.

​ Square Root of 17 is: <span id="p1"></span>


​ <script>
​ document.getElementById('p1').innerHTML=Math.sqrt(17);
​ </script>

Output:

Square Root of 17 is: 4.123105625617661

Math.random()
The JavaScript math.random() method returns the random number between
0 to 1.

​ Random Number is: <span id="p2"></span>


​ <script>
​ document.getElementById('p2').innerHTML=Math.random();
​ </script>

Output:

Random Number is: 0.5884515488433562

Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given
number. For example 3 for 3.7, 5 for 5.9 etc.

​ Floor of 4.6 is: <span id="p4"></span>


​ <script>
​ document.getElementById('p4').innerHTML=Math.floor(4.6);
​ </script>

Output:
Floor of 4.6 is: 4

Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given
number. For example 4 for 3.7, 6 for 5.9 etc.

​ Ceil of 4.6 is: <span id="p5"></span>


​ <script>
​ document.getElementById('p5').innerHTML=Math.ceil(4.6);
​ </script>

Output:

Ceil of 4.6 is: 5

Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest
for the given number. If fractional part is equal or greater than 0.5, it goes to
upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9
etc.

​ Round of 4.3 is: <span id="p6"></span><br>


​ Round of 4.7 is: <span id="p7"></span>
​ <script>
​ document.getElementById('p6').innerHTML=Math.round(4.3);
​ document.getElementById('p7').innerHTML=Math.round(4.7);
​ </script>

Output:

Round of 4.3 is: 4

Round of 4.7 is: 5

Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given
number. For example 4 for -4, 6.6 for -6.6 etc.

​ Absolute value of -4 is: <span id="p8"></span>


​ <script>
​ document.getElementById('p8').innerHTML=Math.abs(-4);
​ </script>

Output:

Absolute value of -4 is: 4

Browser Object Model


The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:

​ window.alert("hello developers");

is same as:

​ alert("hello developers");

Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.

Methods of window object


The important methods of window object are as follows:

Method Description
alert() displays the alert box containing
message with ok button.

confirm() displays the confirm dialog box


containing message with ok and
cancel button.

prompt() displays a dialog box to get input


from the user.

open() opens the new window.

setTimeout() performs action after specified


time like calling function,
evaluating expressions etc.

Example of alert() in javascript


It displays alert dialog box. It has message and ok button.

​ <script type="text/javascript">
​ function msg(){
​ alert("Hello Alert Box");
​ }
​ </script>
​ <input type="button" value="click" onclick="msg()"/>
Example of confirm() in javascript
It displays the confirm dialog box. It has message with ok and cancel buttons.

​ <script type="text/javascript">
​ function msg(){
​ var v= confirm("Are u sure?");
​ if(v==true){
​ alert("ok");
​ }
​ else{
​ alert("cancel");
​ }

​ }
​ </script>

​ <input type="button" value="delete record" onclick="msg()"/>

Example of prompt() in javascript


It displays prompt dialog box for input. It has message and textfield.

​ <script type="text/javascript">
​ function msg(){
​ var v= prompt("Who are you?");
​ alert("I am "+v);

​ }
​ </script>

​ <input type="button" value="click" onclick="msg()"/>
Example of open() in javascript
It displays the content in a new window.

​ <script type="text/javascript">
​ function msg(){
​ open("http://www.facebook.com");
​ }
​ </script>
​ <input type="button" value="facebook" onclick="msg()"/>

Example of setTimeout() in javascript


It performs its task after the given milliseconds.

​ <script type="text/javascript">
​ function msg(){
​ setTimeout(
​ function(){
​ alert("Welcome to Javascript programing after 5 seconds")
​ },2000);

​ }
​ </script>

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

JavaScript Navigator Object


The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

​ window.navigator

Or,

​ navigator

Property of JavaScript navigator object


There are many properties of navigator object that returns information of the
browser.

No. Property Description

1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is


enabled otherwise
false

5 userAgent returns the user agent


6 language returns the language.
It is supported in
Netscape and Firefox
only.

7 userLanguage returns the user


language. It is
supported in IE only.

8 plugins returns the plugins. It


is supported in
Netscape and Firefox
only.

9 systemLanguage returns the system


language. It is
supported in IE only.

10 mimeTypes[] returns the array of


mime type. It is
supported in Netscape
and Firefox only.

11 platform returns the platform


e.g. Win32.

12 online returns true if browser


is online otherwise
false.
Example of navigator object
Let’s see the different usage of history object.

​ <script>
​ document.writeln("<br/>navigator.appVersion:
"+navigator.appVersion);
​ document.writeln("<br/>navigator.cookieEnabled:
"+navigator.cookieEnabled);
​ document.writeln("<br/>navigator.language: "+navigator.language);
​ document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
​ document.writeln("<br/>navigator.platform: "+navigator.platform);
​ document.writeln("<br/>navigator.onLine: "+navigator.onLine);
​ </script>

navigator.appVersion: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36

(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36

navigator.cookieEnabled: true

navigator.language: en-US

navigator.userAgent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36

(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36

navigator.platform: Win32

navigator.onLine: true

JavaScript Screen Object


The JavaScript screen object holds information of browser screen. It can be
used to display screen width, height, colorDepth, pixelDepth etc.

Property of JavaScript Screen Object


There are many properties of screen object that returns information of the
browser.

No. Property Description

1 width returns the width of


the screen

2 height returns the height of


the screen
Example of JavaScript Screen Object

​ <script>
​ document.writeln("<br/>screen.width: "+screen.width);
​ document.writeln("<br/>screen.height: "+screen.height);

​ </script>

screen.width: 1366

screen.height: 768

Document Object Model


The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document


object. It is the root element that represents the html document. It has
properties and methods. By the help of document object, we can add
dynamic content to our web page.

As mentioned earlier, it is the object of window. So

​ window.document

Is same as

​ document

Properties of document object


Let's see the properties of document object that can be accessed and
modified by the document object.
Methods of document object
We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the


doucment.

writeln("string") writes the given string on the


doucment with newline character
at the end.

getElementById() returns the element having the


given id value.

getElementsByName() returns all the elements having the


given name value.

getElementsByTagName() returns all the elements having the


given tag name.

getElementsByClassName() returns all the elements having the


given class name.
Accessing field value by document object

Let's see the simple example of document object that prints name with
welcome message.

​ <script type="text/javascript">
​ function printvalue(){
​ var name=document.form1.name.value;
​ alert("Welcome: "+name);
​ }
​ </script>

​ <form name="form1">
​ Enter Name:<input type="text" name="name"/>
​ <input type="button" onclick="printvalue()" value="print name"/>
​ </form>

In this example, we are going to get the value of input text by user. Here, we
are using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.
Javascript - document.getElementById()
method

The document.getElementById() method returns the element of specified id.

In the previous page, we have used document.form1.name.value to get the


value of the input value. Instead of this, we can use
document.getElementById() method to get value of the input text. But we
need to define id for the input field.

Let's see the simple example of document.getElementById() method that


prints cube of the given number.

​ <script type="text/javascript">
​ function getcube(){
​ var number=document.getElementById("number").value;
​ alert(number*number*number);
​ }
​ </script>
​ <form>
​ Enter No:<input type="text" id="number" name="number"/><br/>
​ <input type="button" value="cube" onclick="getcube()"/>
​ </form>

Javascript -
document.getElementsByName() method
The document.getElementsByName() method returns all the element of
specified name.
The syntax of the getElementsByName() method is given below:

​ document.getElementsByName("name")

Here, name is required.

Example of document.getElementsByName() method


In this example, we going to count total number of genders. Here, we are
using getElementsByName() method to get all the genders.

​ <script type="text/javascript">
​ function totalelements()
​ {
​ var allgenders=document.getElementsByName("gender");
​ alert("Total Genders:"+allgenders.length);
​ }
​ </script>
​ <form>
​ Male:<input type="radio" name="gender" value="male">
​ Female:<input type="radio" name="gender" value="female">

​ <input type="button" onclick="totalelements()" value="Total
Genders">
​ </form>

Javascript -
document.getElementsByTagName()
method
The document.getElementsByTagName() method returns all the element of
specified tag name.
The syntax of the getElementsByTagName() method is given below:

​ document.getElementsByTagName("name")

Here, name is required.

Example of document.getElementsByTagName() method


In this example, we going to count total number of paragraphs used in the
document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total
paragraphs.

​ <script type="text/javascript">
​ function countpara(){
​ var totalpara=document.getElementsByTagName("p");
​ alert("total p tags are: "+totalpara.length);

​ }
​ </script>
​ <p>This is a pragraph</p>
​ <p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
​ <p>Let's see the simple example</p>
​ <button onclick="countpara()">count paragraph</button>

AD

Another example of document.getElementsByTagName()


method
In this example, we going to count total number of h2 and h3 tags used in the
document.

​ <script type="text/javascript">
​ function counth2(){
​ var totalh2=document.getElementsByTagName("h2");
​ alert("total h2 tags are: "+totalh2.length);
​ }
​ function counth3(){
​ var totalh3=document.getElementsByTagName("h3");
​ alert("total h3 tags are: "+totalh3.length);
​ }
​ </script>
​ <h2>This is h2 tag</h2>
​ <h2>This is h2 tag</h2>
​ <h3>This is h3 tag</h3>
​ <h3>This is h3 tag</h3>
​ <h3>This is h3 tag</h3>
​ <button onclick="counth2()">count h2</button>
​ <button onclick="counth3()">count h3</button>

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.

Syntax

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


Example: Inline JavaScript with Event Handlers
In the code below, we have created the <button> element. Also, we have
used the 'onclick' event handler to capture the click event on the button.

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

<html>

<body>

<h2> Click the button to Change its text's color </h2>

<button onclick = "this.style.color='red'"> Click Me </button>

<div id = "output"> </div>

</body>

</html>

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.
<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>
Example: Multiple Functions with Event Handlers
In the code below, we have added the 'ommouseenter' event handler
with the <div> element. We call the changeFontSize() and
changeColor() functions when a user enters the mouse cursor in the
<div> element.

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


changeColor() function changes the color of the text.

This way, you can invoke the multiple functions on the particular
event.

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

</html>

JavaScript Event Object


The function that handles the event takes the 'event' object as a
parameter. The 'event' object contains the information about the
event and the element on which it occurred.

Object Description

Event It is a parent of all event objects.

Here is the list of different types of event objects. Each event object
contains various events, methods, and properties.

Object/Type Handles

AnimationEvent It handles the CSS animations.

ClipboardEvent It handles the changes of the clipboard.

DragEvent It handles the drag-and-drop events.

FocusEvent To handle the focus events.


HashChangeEven It handles the changes in the anchor part of the
t URL.

InputEvent To handle the form inputs.

KeyboardEvent To handle the keyboard interaction by users.

MediaEvent It handles the media-related events.

MouseEvent To handle the mouse interaction by users.

PageTransitionEv To handle the navigation between web pages.


ent

PopStateEvent It handles the changes in the page history.

ProgressEvent To handle the progress of the file loading.

StorageEvent To handle changes in the web storage.

TouchEvent To handle touch interaction on the devices


screen.

TransitionEvent To handle CSS transition.

UiEvent To handle the user interface interaction by


users.

WheelEvent To handle the mouse-wheel interaction by


users.

JavaScript - DOM Events


The DOM events are actions that can be performed on HTML
elements. When an event occurs, it triggers a JavaScript function.
This function can then be used to change the HTML element or
perform other actions.

Here are some examples of DOM events:

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



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

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

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

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.

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

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.

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

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.

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

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.

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

HTML 5 Standard DOM Events


The standard HTML 5 events are listed here for your reference. Here
script indicates a Javascript function to be executed against that
event.

Attribute Value Description

Offline script Triggers when the document goes


offline

Onabort script Triggers on an abort event

onafterprint script Triggers after the document is


printed

onbeforeonload script Triggers before the document


loads

onbeforeprint script Triggers before the document is


printed

onblur script Triggers when the window loses


focus

Triggers when media can start


oncanplay script play, but might has to stop for
buffering

Triggers when media can be


oncanplaythroug
script played to the end, without
h
stopping for buffering

onchange script Triggers when an element changes


onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is


triggered

ondblclick script Triggers on a mouse double-click

ondrag script Triggers when an element is


dragged

ondragend script Triggers at the end of a drag


operation

Triggers when an element has


ondragenter script been dragged to a valid drop
target

Triggers when an element is being


ondragleave script
dragged over a valid drop target

ondragover script Triggers at the start of a drag


operation

ondragstart script Triggers at the start of a drag


operation

ondrop script Triggers when dragged element is


being dropped

ondurationchang script Triggers when the length of the


e media is changed

Triggers when a media resource


onemptied script
element suddenly becomes empty.

onended script Triggers when media has reach


the end
onerror script Triggers when an error occur

onfocus script Triggers when the window gets


focus

onformchange script Triggers when a form changes

onforminput script Triggers when a form gets user


input

onhaschange script Triggers when the document has


change

oninput script Triggers when an element gets


user input

oninvalid script Triggers when an element is


invalid

onkeydown script Triggers when a key is pressed

onkeypress script Triggers when a key is pressed


and released

onkeyup script Triggers when a key is released

onload script Triggers when the document loads

onloadeddata script Triggers when media data is


loaded

Triggers when the duration and


onloadedmetada
script other media data of a media
ta
element is loaded

Triggers when the browser starts


onloadstart script
to load the media data
onmessage script Triggers when the message is
triggered

onmousedown script Triggers when a mouse button is


pressed

onmousemove script Triggers when the mouse pointer


moves

Triggers when the mouse pointer


onmouseout script
moves out of an element

Triggers when the mouse pointer


onmouseover script
moves over an element

onmouseup script Triggers when a mouse button is


released

onmousewheel script Triggers when the mouse wheel is


being rotated

onoffline script Triggers when the document goes


offline

onoine script Triggers when the document


comes online

ononline script Triggers when the document


comes online

onpagehide script Triggers when the window is


hidden

onpageshow script Triggers when the window


becomes visible
onpause script Triggers when media data is
paused

onplay script Triggers when media data is going


to start playing

onplaying script Triggers when media data has


start playing

onpopstate script Triggers when the window's


history changes

Triggers when the browser is


onprogress script
fetching the media data

Triggers when the media data's


onratechange script
playing rate has changed

onreadystatecha script Triggers when the ready-state


nge changes

onredo script Triggers when the document


performs a redo

onresize script Triggers when the window is


resized

Triggers when an element's


onscroll script
scrollbar is being scrolled

Triggers when a media element's


onseeked script seeking attribute is no longer true,
and the seeking has ended

Triggers when a media element's


onseeking script seeking attribute is true, and the
seeking has begun
onselect script Triggers when an element is
selected

Triggers when there is an error in


onstalled script
fetching media data

onstorage script Triggers when a document loads

onsubmit script Triggers when a form is submitted

Triggers when the browser has


been fetching media data, but
onsuspend script
stopped before the entire media
file was fetched

ontimeupdate script Triggers when media changes its


playing position

onundo script Triggers when a document


performs an undo

onunload script Triggers when the user leaves the


document

Triggers when media changes the


onvolumechange script volume, also when volume is set
to "mute"

Triggers when media has stopped


onwaiting script
playing, but is expected to resume
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.

Common Mouse Events


Following are the most common JavaScript mouse events:

Mouse Description
Event

Click When an element experiences the press of a mouse


button, it triggers the click event.

Double The dblclick event fires upon the rapid double-clicking


Click of a mouse button.

Mouse The initiation of a mouse click triggers the


Down 'mousedown' event, while the completion of that click
and causes the 'mouseup' event to occur.
Mouse Up

Mouse When the mouse pointer moves over an element, it


Move triggers the 'mousemove' event; this event supplies
developers with positional information about the
mouse. This data empowers them to devise responsive
interfaces that are rooted in dynamic mouse
movements.
Context When the user attempts to open the context menu,
Menu typically by right-clicking, they trigger the contextmenu
event. This event allows developers to customize or
inhibit default behaviour of the context menu.

Wheel When the mouse wheel rotates, it fires the 'wheel


event'; this particular event commonly manifests in
implementing features, notably zooming or scrolling.

Drag and Events like dragstart, dragend, dragover, dragenter,


Drop dragleave, and drop are associated with drag-and-drop
functionality. They allow developers to create
interactive interfaces for dragging elements within a
web page.

Click Event
In this example we demonstrate the click event. When the button is
clicked, it prints an appropriate message to the console message i.e.
Clicked!. This event is often used while submitting forms.

<!DOCTYPE html>

<html>

<head>

<title>Click Event Example</title>

</head>

<body>

<button id="clickButton">Click me!</button>


<p id = "output"></p>

<script>

const clickButton = document.getElementById('clickButton');

const outputDiv = document.getElementById("output");

clickButton.addEventListener('click', function(event) {

outputDiv.innerHTML += 'Clicked!'+ JSON.stringify(event) + "<br>";

});

</script>

</body>

</html>

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>

You might also like