FSD [CS305]
Module-1: Events & JSON
Events, Different Types of Events, How to Bind an Event to an Element, Event Delegation,
Event Listeners.
JSON: Working with JSON data.
Activity: Write the Java script file to read and write the JSON data from and to console.
What are Events?
Events are things that happen in the browser when the user interacts with a web page or when the
browser itself performs an action.
Examples:
o User clicks a button
o Mouse moves over an element
o A web page finishes loading
o A form is submitted
👉 JavaScript can be used to respond to these events by running functions (called event handlers).
Types of Events
• UI Events- occurs when the user interacts with the browser window or web page Interface
• Keyboard Events – Occurs when a user interacts with the keyboard
• Mouse Events – Occurs when a user interacts with the mouse or touchscreen
• Focus Events – Occurs when an element gains or loses focus
• Form Events – Occurs when a user interacts with a form element
• Mutation Events – Occurs when the DOM structure has been changed by a script
1. UI Events
Event Description
Triggered when the entire page (including images, scripts) has
load
loaded.
unload Triggered when the page is being unloaded or closed.
error Triggered when a resource (like image or script) fails to load.
resize Triggered when the browser window is resized.
scroll Triggered when the user scrolls the page or an element.
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
1. load - Occurs when the entire web page (including images, scripts, styles) has finished loading.
Useful for running scripts after everything is ready.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Load Event</title>
<script>
window.onload = function() {
alert("Page fully loaded!");
};
</script>
</head>
<body>
<h2>Welcome</h2>
</body>
</html>
2. unload - Triggered when the user leaves the page (closing tab, navigating away, or refreshing).
Often used for cleanup, but modern browsers limit alerts/popups here.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Unload Event</title>
<script>
window.onunload = function() {
console.log("Page is unloading...");
};
</script>
</head>
<body>
<h2>Close or refresh this page to see console message</h2>
</body>
</html>
3. error - Occurs when an error happens while loading an external resource (like an image or script).
Example:
<!DOCTYPE html>
<html>
<head>
<title>Error Event</title>
</head>
<body>
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
<img src="wrongpath.jpg" onerror="alert('Image failed to load!')">
</body>
</html>
4. resize - Triggered when the browser window is resized.
Useful for responsive design adjustments.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Resize Event</title>
<script>
window.onresize = function() {
document.body.style.backgroundColor = "lightblue";
};
</script>
</head>
<body>
<h2>Resize the window to change background color</h2>
</body>
</html>
5. scroll - Occurs when the user scrolls the document or an element with scrollbars.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Scroll Event</title>
<script>
window.onscroll = function() {
console.log("You are scrolling!");
};
</script>
</head>
<body style="height:1200px;">
<h2>Scroll down to trigger the event (check console)</h2>
</body>
</html>
2. Keyboard Events
Event Description
Fires when a key is pressed down. Works
keydown
for all keys including arrows, Ctrl, etc.
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
keyup Fires when a key is released.
Fires when a key is pressed, but only for
keypress character keys (deprecated in modern
browsers).
Example :
<!DOCTYPE html>
<html>
<head>
<title>Keyboard Events</title>
</head>
<body>
<h2>Press any key and check the output:</h2>
<div id="output" style="font-size:18px; color:blue;"></div>
<script>
// JavaScript Section
document.onkeydown = function(event) {
document.getElementById("output").innerHTML =
"KeyDown: " + event.key;
};
document.onkeypress = function(event) {
document.getElementById("output").innerHTML +=
"<br>KeyPress: " + event.key;
};
document.onkeyup = function(event) {
document.getElementById("output").innerHTML +=
"<br>KeyUp: " + event.key + "<hr>";
};
</script>
</body>
</html>
3. Mouse Events
Event Description
User presses and releases a button over the same
click
element
User presses and releases a button twice over the same
dbclick
element
mousedown User presses a mouse button while over an element
mouseup User releases a mouse button while over an element
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
mousemove User moves the mouse
mouseover User moves the mouse over an element (not on a
touchscreen)
mouseout User moves the mouse off an element (not on a
touchscreen)
Example:
<!DOCTYPE html>
<html>
<head>
<title>Mouse Events Example</title>
<style>
#box {
width: 300px;
height: 200px;
border: 2px solid blue;
margin: 20px;
text-align: center;
line-height: 200px;
font-size: 18px;
}
</style>
</head>
<body>
<h2>Mouse Events Demo</h2>
<div id="box">Hover / Click Here</div>
<p id="output">Event: None</p>
<script>
let box = document.getElementById("box");
let output = document.getElementById("output");
box.addEventListener("click", () => output.innerText = "Event: Click");
box.addEventListener("dblclick", () => output.innerText = "Event: Double Click");
box.addEventListener("mousedown", () => output.innerText = "Event: Mouse Down");
box.addEventListener("mouseup", () => output.innerText = "Event: Mouse Up");
box.addEventListener("mousemove", () => output.innerText = "Event: Mouse Move");
box.addEventListener("mouseover", () => output.innerText = "Event: Mouse Over");
box.addEventListener("mouseout", () => output.innerText = "Event: Mouse Out");
</script>
</body>
</html>
4. Focus Events
Event Description
Focus/focus in Element gains focus
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
Blur/ focus out Element loses focus
Example :
<!DOCTYPE html>
<html>
<head>
<title>Focus and Blur Example</title>
</head>
<body>
<h2>Focus / Blur Events</h2>
<input type="text" id="name" placeholder="Enter your name">
<p id="msg">Event: None</p>
<script>
let input = document.getElementById("name");
let msg = document.getElementById("msg");
// focus and focusin
input.addEventListener("focus", () => msg.innerText = "Event: focus");
input.addEventListener("focusin", () => msg.innerText = "Event: focusin");
// blur and focusout
input.addEventListener("blur", () => msg.innerText = "Event: blur");
input.addEventListener("focusout", () => msg.innerText = "Event: focusout");
</script>
</body>
</html>
5. Form Events
Event Description
input Value in any <input> or <textarea> element has changed
change Value in select box, checkbox, or radio button changes
submit User submits a form
reset User clicks on a form’s reset button
cut User cuts content from a form field
copy User copies content from a form field
paste User pastes content into a form field
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
select User selects some text in a form field
Example :
<!DOCTYPE html>
<html>
<head>
<title>Form Events Example</title>
</head>
<body>
<h2>Form Events Demo</h2>
<form id="myForm">
<label>Enter Name: </label>
<input type="text" id="name"><br><br>
<label>Select City: </label>
<select id="city">
<option value="">--Choose--</option>
<option>Bangalore</option>
<option>Mumbai</option>
<option>Delhi</option>
</select><br><br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<p id="msg">Event: None</p>
<script>
let nameField = document.getElementById("name");
let cityField = document.getElementById("city");
let form = document.getElementById("myForm");
let msg = document.getElementById("msg");
// input event
nameField.addEventListener("input", () => msg.innerText = "Event: input");
// change event
cityField.addEventListener("change", () => msg.innerText = "Event: change");
// submit event
form.addEventListener("submit", (e) => {
e.preventDefault(); // prevent refresh
msg.innerText = "Event: submit";
});
// reset event
form.addEventListener("reset", () => msg.innerText = "Event: reset");
// cut, copy, paste
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
nameField.addEventListener("cut", () => msg.innerText = "Event: cut");
nameField.addEventListener("copy", () => msg.innerText = "Event: copy");
nameField.addEventListener("paste", () => msg.innerText = "Event: paste");
// select event
nameField.addEventListener("select", () => msg.innerText = "Event: select");
</script>
</body>
</html>
6. Mutation Events
Event Description
DOMSubtreeModified Change has been made to the document
Node has been inserted as a direct child of
DOMNodeInserted
another node
DOMNodeRemoved Node has been removed from another node
DOMNodeInsertedInto Node has been inserted as a descendant of
Document another node
DOMNodeRemovedFro Node has been removed as a descendant of
mDocument another node
Example :
<!DOCTYPE html>
<html>
<head>
<title>DOM Mutation Events</title>
</head>
<body>
<h2>DOM Events Demo</h2>
<div id="container">Hello</div>
<button onclick="addNode()">Add</button>
<button onclick="removeNode()">Remove</button>
<script>
let container = document.getElementById("container");
container.addEventListener("DOMSubtreeModified", () => console.log("DOMSubtreeModified"));
container.addEventListener("DOMNodeInserted", () => console.log("DOMNodeInserted"));
container.addEventListener("DOMNodeRemoved", () => console.log("DOMNodeRemoved"));
container.addEventListener("DOMNodeInsertedIntoDocument", () =>
console.log("DOMNodeInsertedIntoDocument"));
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
container.addEventListener("DOMNodeRemovedFromDocument", () =>
console.log("DOMNodeRemovedFromDocument"));
function addNode() {
let p = document.createElement("p");
p.textContent = "New Node";
container.appendChild(p);
}
function removeNode() {
if (container.lastChild && container.lastChild.tagName === "P") {
container.removeChild(container.lastChild);
}
}
</script>
</body>
</html>
JavaScript Event Handling - 3 Essential Steps
Step 1: Select the Element
• Identify the DOM node you want to respond to user interactions
• Use DOM queries to target specific HTML elements (links, buttons, forms, etc.)
Step 2: Specify the Event
• Define which user action will trigger the response (click, hover, submit, etc.)
• This process is called "binding an event to a DOM node“
Step 3: Define the Response Code
• Write the JavaScript function that executes when the event occurs
• Can be either a named function or an anonymous function
Key Concept: Event handling enables interactive web pages by connecting user actions to JavaScript
responses through this three-step process.
How to Bind an Event to an Element
Event binding refers to the process of attaching an event (such as click, mouseover, or keydown) directly
to an HTML element. When the event occurs, a function executes in response.
Ways to Bind Events
1. Inline Event Binding (Inside HTML)
2. JavaScript Event Binding (Using onclick)
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
3. Using addEventListener (Modern approach)
1: Inline Event Binding
In this method, the event handler is written directly inside the HTML element as an attribute.
The attribute name starts with on (like onclick, onmouseover, onchange) and contains the
JavaScript code to be executed.
Eg:
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() { alert("Button Clicked!");
}
</script>
Drawback: Not recommended because it mixes HTML and JavaScript, reducing code readability and
maintainability.
2: JavaScript Event Binding
In this method, first select the HTML element using JavaScript, then bind the event by setting its
event property (like .onclick, .onmouseover).
Eg:
<button id="myButton">Click Me</button>
<script>
document.getElementById("myButton").onclick = function() {
alert("Button Clicked!");
};
</script>
Drawback: If another function is assigned to onclick, it replaces the existing one.
3: Using addEventListener (Best Practice)
This is the recommended and modern way of handling events in JavaScript.
You use the addEventListener(event, handler) method to attach event listeners to elements.
Eg:
<button id="btn">Click Me</button>
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
<script>
document.getElementById("btn").addEventListener("click", function() {
alert("Event Listener Clicked!");
});
</script>
Advantages:
Supports multiple event handlers on the same element.
More flexible than the onclick property.
Event Delegation
Event Delegation is a technique where a single event listener is added to a parent element, and it
handles events from its child elements.
Instead of attaching an event to each child individually, we attach it once to the parent.
Why Use Event Delegation
Performance: fewer event listeners → faster execution.
Dynamic Elements: works even if new child elements are added later.
Less Repetition: avoids writing the same code multiple times.
How It Works
Events bubble up from the child element to its ancestors.
The parent listens for events and uses event.target to detect which child triggered it.
Event Delegation program
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
</head>
<body>
<h2>Event Delegation Demo</h2>
<div id="parent">
<div class="child">Box 1</div>
<div class="child">Box 2</div>
<div class="child">Box 3</div>
</div>
<script>
// Event Delegation: Add listener to parent
document.getElementById("parent").addEventListener("click", function(event) {
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
if(event.target.classList.contains("child")) {
alert("You clicked: " + event.target.textContent);
}
});
</script>
</body>
</html>
Event Propagation or Event Flow
Event propagation refers to how events are transmitted through elements in the DOM.
The process occurs in three distinct phases:
Capturing phase: The event moves from the top ancestor down to the target element.
Target phase: The event reaches the actual target element where the user action occurred.
Bubbling phase: Afterwards, the event rises from the target back up through its parent elements to
the top.
Understanding these three phases is crucial for controlling how and when elements respond to events in
web applications.
Event Capturing (Trickling Down)
Event capturing is when the event travels from the outermost parent down to the target element.
This approach is less commonly used but is valuable for early interception of events before they reach the
target.
To use capturing in JavaScript, set the capture option to true in the addEventListener() method:
text
parent.addEventListener("click", captureHandler, true);
Capturing is ideal when there is a need to act before a child element gets the event.
Event Bubbling (Rising Up)
Event bubbling is the default behavior in JavaScript.
Here, the event begins at the target element and moves up through its parent elements.
Most event handlers are processed during this phase, which allows parent elements to react to events
triggered on their children.
parent.addEventListener("click", bubbleHandler, false);
// Or:
parent.addEventListener("click", bubbleHandler);
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
Event Listeners
Event Listener is a method in JavaScript (commonly addEventListener()) that is used to attach one or
more functions to specific events on an element.
It allows multiple events (e.g., click, mouseover, mouseout) to be attached to the same element without
overwriting each other. When the event occurs, the corresponding function (callback) is executed.
Syntax:
element.addEventListener(event, function, useCapture);
event → The type of event (e.g., "click", "mouseover").
function → The callback function to run when the event occurs.
useCapture → (Optional) Boolean that specifies event flow (default: false).
Example: Multiple Events on the Same Element
<button id="eventBtn">Hover or Click Me</button>
<script>
let button = document.getElementById("eventBtn");
// Click event
button.addEventListener("click", function() {
alert("Button Clicked!");
});
// Mouseover event
button.addEventListener("mouseover", function() {
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
button.style.backgroundColor = "lightblue";
});
// Mouseout event
button.addEventListener("mouseout", function() {
button.style.backgroundColor = "";
});
</script>
Using Parameters with Event Listeners
1. Event Listener Without Parameters
We can directly assign a function reference when no parameters are needed.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Event Listener Without Parameters</title>
</head>
<body>
<h2>Click the button to show a message</h2>
<button id="showBtn">Show Message</button>
<script>
function showMessage() {
alert("This is a simple message!");
}
var button = document.getElementById('showBtn');
button.addEventListener('click', showMessage); // Event Listener Without Parameter
</script>
</body>
</html>
When the button is clicked → showMessage() executes.
Problem With Parameters
If we try to pass parameters directly, like:
element.addEventListener('click', myFunction(10));
The function executes immediately during page load, instead of waiting for the event.
2. Event Listener With Parameters (Correct Way)
Use a wrapper function (anonymous function) to pass parameters:
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
<!DOCTYPE html>
<html>
<head>
<title>Event Listener With Parameters</title>
</head>
<body>
<h2>Click the button to greet the user</h2>
<button id="greetBtn">Greet</button>
<script>
function greetUser(name) {
alert("Hello, " + name + "!");
}
var button = document.getElementById('greetBtn');
button.addEventListener('click', function() {
greetUser('Sunil'); // Event Listener With Parameter
});
</script>
</body>
</html>
Note:
Without parameters → pass the function reference directly.
With parameters → wrap the function inside an anonymous function.
This ensures the function executes only when the event actually occurs.
Event Object
An event object is created whenever something happens on a webpage (e.g., a button is clicked, a key is
pressed, a link is hovered).
It contains details about the event and the element that triggered it.
Example: Clicking a button → event object tells us which button was clicked.
Using the Event Object
Event objects are automatically passed to event-handling functions.
Inside the function, we usually name it e or event.
Example:
button.addEventListener("click", function(e) {
console.log(e.target); // shows which element was clicked
});
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
Importance of Event Object
Provides details about the event, such as:
o Which key was pressed
o Which element was clicked
Gives control over the browser’s behavior:
o Stop actions (e.g., stop a link from opening).
o Change behavior (e.g., prevent a form from submitting).
Event Properties
Property Purpose
target The actual element on which the event occurred
type Type of the event (e.g., click, keydown)
cancelable Whether the event's default action can be prevented
Event Methods
Method Purpose
preventDefault() Cancels default behavior (if allowed)
stopPropagation() Stops the event from bubbling or capturing further
JSON
JSON is a lightweight data format used for storing and exchanging data between systems.
It is easy for humans to read and write, and easy for machines to parse and generate.
Widely used in web development for communication between client (browser) and server
(backend).
Standard format for APIs, AJAX, and RESTful services.
Language-independent, but syntax is similar to JavaScript, so it works across many
programming languages.
Preferred over XML due to its simplicity and smaller size.
Data Types Supported in JSON
JSON supports a limited set of data types:
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
1. String → "Sunil"
2. Number → 20 (both integers and floating point numbers)
3. Boolean → true or false
4. Null → null
5. Array → ["Python", "JavaScript", "C++"] (ordered list of values)
6. Object → {"id": 1, "name": "Sunil"} (collection of key–value pairs)
Example :
const studentProfile = {
"name": "Sunil",
"age": 20,
"skills": ["Python", "JavaScript"],
"isStudent": true,
"graduated": null
};
Reading and Writing JSON
Two main methods in JavaScript:
1. JSON.stringify()
Converts a JavaScript object into a JSON string.
Commonly used when sending data to a server.
const studentProfile = {
name: "Sunil",
age: 20,
skills: ["Python", "JavaScript"],
isStudent: true
};
const jsonString = JSON.stringify(studentProfile);
console.log(jsonString);
// {"name":"Sunil", "age":20, "skills":["Python","JavaScript"], "isStudent":true}
2. JSON.parse()
Converts a JSON string back into a JavaScript object.
Commonly used when receiving data from a server.
const jsonString = '{"name":"Sunil","age":20,"skills":["Python","JavaScript"],"isStudent":true}';
Prof. Sunil Kumar K N , Dept. of ISE, CITech
FSD [CS305]
const studentObj = JSON.parse(jsonString);
console.log(studentObj.name); // Sunil
console.log(studentObj.skills); // ["Python", "JavaScript"]
Note :
JSON supports only a limited set of data types: string, number, boolean, null, array, object.
Keys must always be written in double quotes.
Use JSON.stringify() before sending data to a server.
Use JSON.parse() after receiving data from a server.
Prof. Sunil Kumar K N , Dept. of ISE, CITech