JavaScript Events
Syntax:
<HTML-element Event-Type = "Action to be performed">
Common JavaScript Events Table
Event Attribute Description
onclick Triggered when an element is clicked.
onmouseover Fired when the mouse pointer moves over an element.
onmouseout Occurs when the mouse pointer leaves an element.
onkeydown Fired when a key is pressed down.
onkeyup Fired when a key is released.
onchange Triggered when the value of an input element changes.
onload Occurs when a page has finished loading.
onsubmit Fired when a form is submitted.
onfocus Occurs when an element gets focus.
onblur Fired when an element loses focus.
<!doctype html>
<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>
<body>
<button type="button" onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>
</html>
Applying onclick using addEventListener() method
Syntax:
[Link]('eventName', callbackFunction);
JavaScript onmouseover and onmouseout: The onmouseover and onmouseout
events occur when the mouse cursor is placed over specific element
Example 1: These events do not require a mouse click to happen
<script type="text/javascript">
function over()
{
[Link]('key').innerHTML=
"Onmouseover event has occurred";
}
function out()
{
[Link]('key').innerHTML=
"Onmouseout event has occurred";
}
</script>
<h2 id="key" onmouseover="over()" onmouseout="out()">
Original Text
</h2>
• In JavaScript, using the addEventListener() method:
[Link]("submit", myScript);
The onsubmit event in HTML DOM occurs after the submission of a form. The
form tag supports this event.
<h1 style="color:green">Javascript</h1>
<h2>HTML DOM onsubmit Event</h2>
<form id="formID" action="#">
Enter name:
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</center>
<script>
[Link](
"formID").addEventListener("submit", hello);
function hello() {
alert("form submitted");
}
</script>
Call back function
A callback function is a function that is passed as an argument to another
function, and it is called (executed) inside the outer function.
A function passed into another function and executed later.
Why use Callback Functions?
• To make JavaScript asynchronous (e.g., wait for data to load, then run a
function).
• To reuse logic.
• To control the sequence of execution.
function outerFunction(callback) {
// some code
callback(); // call the function passed as argument
}
function sayHello() {
[Link]("Hello!");
}
outerFunction(sayHello);
Example
function greetUser(name, callback) {
[Link]("Hello, " + name);
callback(); // call the second function
}
function sayBye() {
[Link]("Goodbye!");
}
greetUser("Anu", sayBye);
Using anonymous call back
function greet(callback) {
[Link]("Welcome!");
callback(); // runs after "Welcome"
}
greet(function () {
[Link]("This is a callback function.");
});
Callback after a delay using setTimeout
function showMessage() {
[Link]("Message shown after 2 seconds");
}
setTimeout(showMessage, 2000); // callback runs after 2 seconds
Array forEach() with callback
let fruits = ["apple", "banana", "mango"];
[Link](function (fruit) {
[Link]("Fruit: " + fruit);
});
Student Marks Processing with Callback
Use a callback function to calculate the total marks and then perform different
operations like:
• Display the total
• Check if the student passed
• Give grade based on total
Imagine you're building a result-processing system for a college. You write a
function to calculate the total marks of a student, but what you do after getting
the total (like pass/fail check or grade assignment) will be passed as a callback
function.
1. Write a function calculateTotal(marks, callback)
o marks is an array of subject marks
o callback is a function to do something with the total
2. Create 3 different callback functions:
o One to display the total
o One to check pass/fail (pass if total ≥ 150)
o One to assign grade based on total
Expected Output
Total Marks: 210
Status: Pass
Grade: A
Solution
// 1. Main function that takes a callback
function calculateTotal(marks, callback) {
let total = 0;
for (let mark of marks) {
total += mark;
}
callback(total); // Use the callback with the result
}
// 2. Callback functions
function displayTotal(total) {
[Link]("Total Marks:", total);
}
function checkPass(total) {
if (total >= 150) {
[Link]("Status: Pass");
} else {
[Link]("Status: Fail");
}
}
function assignGrade(total) {
let grade = '';
if (total >= 200) grade = 'A';
else if (total >= 150) grade = 'B';
else grade = 'C';
[Link]("Grade:", grade);
}
// 3. Marks array (sample data)
let studentMarks = [70, 65, 75];
// 4. Function calls with different callbacks
calculateTotal(studentMarks, displayTotal);
calculateTotal(studentMarks, checkPass);
calculateTotal(studentMarks, assignGrade);
What is the Event Loop?
The Event Loop is a core concept in JavaScript that enables asynchronous
behavior, even though JavaScript is a single-threaded language (i.e., it executes
one thing at a time).
It helps JavaScript wait for tasks (like API calls, timers, user inputs) without
blocking other operations.
Key Terms:
Term Description
Call Stack Where functions are executed one at a time (LIFO order).
Browser-provided features like setTimeout, DOM events, fetch,
Web APIs
etc.
Callback
Stores functions waiting to run after async tasks finish.
Queue
Continuously checks if the call stack is empty and pushes
Event Loop
queued callbacks.
1. JavaScript executes code in the Call Stack.
2. When an asynchronous function is called (like setTimeout()), it's sent to
the Web API.
3. Once it finishes (after time or event), its callback goes to the Callback
Queue.
4. The Event Loop checks if the stack is empty.
5. If empty, it pushes the callback from the queue to the call stack for
execution.
Simple Example of Event Loop:
[Link]("1: Start");
setTimeout(function () {
[Link]("2: Inside setTimeout");
}, 2000); // Waits 2 seconds
[Link]("3: End");
1: Start
3: End
2: Inside setTimeout
Why?
• [Link]("1: Start") → runs immediately.
• setTimeout() is sent to Web APIs → it waits 2 seconds.
• [Link]("3: End") → runs immediately after setTimeout is registered.
• After 2 seconds, the callback from setTimeout goes to the queue, then to
the stack.
• Finally, "2: Inside setTimeout" prints.
Mixing Synchronous and Asynchronous
[Link]("A");
setTimeout(() => {
[Link]("B");
}, 0);
[Link]("C");
Even though setTimeout is set to 0, it goes to the Web API and callback queue.
The event loop only executes it after the synchronous code (A, C) is done.
Component Role
Call Stack Executes JS code one at a time
Web APIs Handles async operations like timers, DOM, fetch
Callback Queue Queues completed async callbacks
Event Loop Sends callbacks to the call stack when it's empty
Example a Food Order System
• [Link]() for sync code
• setTimeout() for async simulation
• Observing order of execution
How food ordering works in a restaurant:
1. Customer places order
2. Restaurant receives and starts preparing (takes time)
3. Order is ready and served
4. Meanwhile, other tasks continue (like welcoming other customers)
Simulate a restaurant where:
• A customer places an order.
• Food preparation takes 3 seconds (simulate using setTimeout).
• While food is being prepared, show other tasks (like welcoming another
customer).
• Show the exact order of log messages.
Expected Output (in Console):
Customer 1: Order placed
Customer 1: Food is being prepared...
Welcome Customer 2
Customer 1: Order served
Solution
function placeOrder(customer) {
[Link](`${customer}: Order placed`);
// Simulating async food preparation
setTimeout(() => {
[Link](`${customer}: Order served`);
}, 3000);
[Link](`${customer}: Food is being prepared...`);
}
// Call the function
placeOrder("Customer 1");
// Simultaneous task
[Link]("Welcome Customer 2");
• Call Stack: Executes [Link]() statements immediately.
• Web APIs: setTimeout() sends the callback to the browser timer.
• Callback Queue: After 3 seconds, the message is queued.
• Event Loop: Waits for the call stack to be empty before running the
queued message.
1. Why does "Welcome Customer 2" appear before "Customer 1: Order
served"?
2. What would happen if you increase the delay in setTimeout()?
3. How does this show non-blocking nature of JS?
Let process multiple orders with different preparation timelines:
function placeOrder(customer, time) {
[Link](`${customer}: Order placed`);
setTimeout(() => {
[Link](`${customer}: Order served`);
}, time);
[Link](`${customer}: Food is being prepared...`);
}
placeOrder("Customer 1", 3000);
placeOrder("Customer 2", 1000);
[Link]("Manager: All orders received");
1 placeOrder("Customer 1") Function call goes on the call stack 2
2 [Link]("Order placed") Executes immediately
3 setTimeout(callback, 3000) Timer started, callback sent to Web API
4 [Link]("Food is being...") Executes immediately
5 [Link]("Welcome Customer 2") Executes immediately
6 (after 3s) callback → Callback Q Timer expires, callback moves to queue
7 Event loop → Executes callback Call stack empty, so callback runs now
API Application Programming Interface
It allows two software programs (like your JavaScript code and a server) to
communicate.
Example:
When you search for weather in Google, your browser talks to a weather API.
We send a request (like "Give me today’s weather") and receive a response (like
"It’s 28°C and sunny").
In JavaScript, we usually use the Fetch API to make that request.
JSON = JavaScript Object Notation
It is a lightweight format to send and receive data. It looks like a JavaScript
object:
Example JSON:
{
"name": "Ravi",
"age": 24,
"skills": ["HTML", "CSS", "JavaScript"]
}
When we get a response from an API, the data is usually in JSON format.
Fetch API – How to use it
The Fetch API allows you to send HTTP requests to get data from a server.
Basic syntax:
fetch("api-url")
.then(response => [Link]())
.then(data => {
// use the data here
})
.catch(error => {
[Link]("Error:", error);
});
A mini app using a real public API: [Link]
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Demo</title>
<style>
body {
font-family: Arial;
padding: 20px;
}
.user-card {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
</style>
</head>
<body>
<h2> User List from Public API</h2>
<button onclick="getUsers()">Load Users</button>
<div id="userList"></div>
<script>
function getUsers() {
// API URL
const url = '[Link]
// Fetch data from API
fetch(url)
.then(response => {
if (![Link]) {
throw new Error("Network response was not ok");
}
return [Link](); // Convert response to JSON
})
.then(data => {
const userList = [Link]('userList');
[Link] = ''; // Clear previous data
// Loop through each user and display their info
[Link](user => {
const userDiv = [Link]('div');
[Link]('user-card');
[Link] = `
<strong>Name:</strong> ${[Link]}<br>
<strong>Email:</strong> ${[Link]}<br>
<strong>Phone:</strong> ${[Link]}<br>
<strong>Company:</strong> ${[Link]}
`;
[Link](userDiv);
});
})
.catch(error => {
[Link]('Error fetching data:', error);
[Link]('userList').innerText = 'Failed to load users.';
});
}
</script>
</body>
</html>
Another example: A simple user registration form
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using Fetch API</title>
<style>
body {
font-family: Arial;
margin: 30px;
}
form {
max-width: 400px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 6px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
padding: 8px;
width: 100%;
margin-bottom: 15px;
}
#result {
margin-top: 20px;
padding: 10px;
border: 1px dashed green;
display: none;
}
</style>
</head>
<body>
<h2> Register User</h2>
<form id="userForm">
<label for="name">Name:</label>
<input type="text" id="name" required>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script>
const form = [Link]('userForm');
const resultDiv = [Link]('result');
[Link]('submit', function(event) {
[Link](); // prevent actual form submission
const name = [Link]('name').value;
const email = [Link]('email').value;
// Prepare the data as JSON
const userData = {
name: name,
email: email
};
// Send POST request
fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](userData)
})
.then(response => [Link]())
.then(data => {
// Show the response in the resultDiv
[Link] = 'block';
[Link] = `
<strong>User submitted!</strong><br>
<strong>ID (fake):</strong> ${[Link]} <br>
<strong>Name:</strong> ${[Link]} <br>
<strong>Email:</strong> ${[Link]}
`;
[Link]();
})
.catch(error => {
[Link] = 'block';
[Link] = ' Error submitting form.';
[Link]('Error:', error);
});
});
</script>
</body>
</html>
1. localStorage in JavaScript
What is localStorage?
• localStorage stores data in the browser with no expiry.
• Even if you close the tab or browser, data is still there.
• It stores data as key-value (like a dictionary).
Syntax
[Link]("key", "value"); // store data
[Link]("key"); // get data
[Link]("key"); // delete specific item
[Link](); // delete all items
Example:
<script>
// Storing data
[Link]("username", "Rakesh");
[Link]("age", "22");
// Retrieving data
let user = [Link]("username");
[Link]("Hi " + user); // Output: Hi Rakesh
// Deleting one item
[Link]("age");
// Clear all // [Link]();
</script>
Note:
• localStorage stores everything as a string.
• So objects or arrays must be converted using [Link]().
Example:
let student = { name: "Raj", age: 21 };
[Link]("student", [Link](student));
To read it back:
let data = [Link]([Link]("student"));
[Link]([Link]); // Raj
2. sessionStorage in JavaScript
What is sessionStorage?
• Same like localStorage, but it lasts only for that session (open tab).
• When user closes the tab, data is deleted automatically.
Example:
<script>
[Link]("color", "blue");
let clr = [Link]("color");
[Link](clr); // blue
[Link]("color");
[Link](); // remove everything
</script>
Summary:
Feature localStorage sessionStorage
Data lifetime Until deleted Until tab closed
Scope All tabs Only current tab
Size limit ~5-10 MB ~5 MB
3. Cookies (brief explanation)
What is a cookie?
• Cookies are small pieces of data stored in the browser.
• Mostly used for: login sessions, remembering preferences, tracking users.
• Expire after a time you set.
Create a Cookie:
[Link] = "username=Ravi";
Set cookie with expiry:
let date = new Date();
[Link]([Link]() + (12460601000)); // 1 day
let expires = "expires=" + [Link]();
[Link] = "user=Anu; " + expires + "; path=/";
Read all cookies:
[Link]([Link]);
• Cookies are sent with every HTTP request, so they can affect
performance.
• Size limit is around 4 KB.
• Best used for login/authentication related data.
[Link]("city", "Hyderabad");
[Link]([Link]("city"));
[Link]("temp", "42");
[Link]([Link]("temp"));
[Link] = "mode=dark";
[Link]([Link]);
localStorage example
1: Store your name, age, and city in localStorage
→ Then retrieve and display them
let name = "Anuradha";
let age = 30;
let city = "Chennai";
[Link]("name", name);
[Link]("age", age);
[Link]("city", city);
[Link]([Link]("name"));
[Link]([Link]("age"));
[Link]([Link]("city"));
2: Store an object in localStorage
→ Save a student object: { name: "Ravi", marks: 89 }
let student = {
name: "Ravi",
marks: 89
};
[Link]("student", [Link](student));
// Retrieve
let s = [Link]([Link]("student"));
[Link]([Link]); // Ravi
3: Remove item from localStorage
[Link]("city");
4: Clear entire localStorage
[Link]();
sessionStorage
1: Save a temporary value like theme = dark
[Link]("theme", "dark");
[Link]([Link]("theme")); // dark
2: Check if user visited this tab before
if ([Link]("visited")) {
[Link]("Welcome back!");
} else {
[Link]("First visit in this tab");
[Link]("visited", "yes");
}
3: Store array of fruits
let fruits = ["apple", "banana", "mango"];
[Link]("fruits", [Link](fruits));
let f = [Link]([Link]("fruits"));
[Link](f[1]); // banana
Login Form with "Remember Me" using localStorage, sessionStorage &
Cookies
If user checks "Remember Me", store username in localStorage
If not, store username in sessionStorage
Also save a cookie called loginStatus = true for 2 days
<body> <h2>Login</h2>
<form id="loginForm"> <label>Username:</label>
<input type="text" id="username" required><br><br>
<input type="checkbox" id="remember"> Remember Me<br><br>
<button type="submit">Login</button>
</form>
<p id="message"></p>
<script> // Load remembered username
[Link] = function() {
let savedName = [Link]("savedUsername");
if (savedName) { [Link]("username").value = savedName;
[Link]("remember").checked = true;
}
}; // On form submit
[Link]("loginForm").addEventListener("submit",
function(e) { [Link]();
let username = [Link]("username").value;
let remember = [Link]("remember").checked;
if (remember) { [Link]("savedUsername", username);
} else { [Link]("tempUsername", username); } // Set a cookie
let d = new Date();
[Link]([Link]() + (2*24*60*60*1000)); // 2 days
let expires = "expires=" + [Link]();
[Link] = "loginStatus=true; " + expires + "; path=/";
[Link]("message").innerText = "Logged in as " + username;
});
</script>
</body>
</html>