Session 5
JavaScript HTML DOM Events and Event Listener
In Session 4, you learned how to access and manipulate HTML elements using the DOM. Session 5 builds upon this foundation by introducing DOM Events, which enable web pages to react dynamically to user actions and browser occurrences. Events are the bridge between static HTML and interactive JavaScript, allowing scripts to execute in response to triggers like mouse clicks, page loads, keyboard input, or form submissions.
This session shifts focus from inline event attributes (e.g., onclick="func()") to the modern, standardized Event Listener API. You will learn how to attach, manage, and remove event handlers using addEventListener() and removeEventListener(), understand event propagation (bubbling vs. capturing), and implement multiple independent listeners on a single element. By the end of this session, you will be able to design responsive, event-driven web interfaces while maintaining clean separation between HTML structure and JavaScript behavior.
Objectives
- Understand common HTML DOM events and their triggers
- Attach event handlers using
addEventListener()without overwriting existing ones - Control event propagation using the
useCaptureparameter (bubbling vs. capturing) - Remove event listeners dynamically using
removeEventListener() - Implement practical event-driven interactions through hands-on exercises
DOM Events
DOM events are signals that something has occurred in the browser or with a specific HTML element. JavaScript can listen for these signals and execute code when they fire.
| Event Category | Common Examples | Trigger |
|---|---|---|
| Mouse | click, dblclick, mouseover, mouseout, mousedown, mouseup | User interacts with pointing device |
| Keyboard | keydown, keyup, keypress | User presses/releases keys |
| Form/Input | change, input, submit, focus, blur | User modifies or submits form data |
| Window/Document | load, DOMContentLoaded, resize, scroll | Page lifecycle or viewport changes |
| Media/Image | load (on <img>), play, pause | Resource state changes |
Event Handling Evolution
| Approach | Syntax | Pros | Cons |
|---|---|---|---|
| Inline HTML | <button onclick="myFunc()"> | Quick to write | Mixes HTML & JS, hard to maintain, overwrites if duplicated |
| DOM Property | btn.onclick = myFunc; | Simple separation | Only allows one handler per event type (overwrites previous) |
| Event Listener | btn.addEventListener("click", myFunc); | Recommended: supports multiple handlers, clean separation, modern standard | Slightly more verbose |
Syntax & Parameters
addEventListener()
element.addEventListener(event, function, useCapture);
| Parameter | Description |
|---|---|
event | String name of the event (e.g., "click", "load", "change") |
function | Callback to execute when event fires (named function or anonymous) |
useCapture | Optional Boolean. false = Bubbling (default), true = Capturing |
Key Advantage: Unlike .onclick =, addEventListener does not overwrite existing handlers. You can attach multiple listeners to the same element for the same event.
// Multiple listeners on one button
btn.addEventListener("click", firstAction);
btn.addEventListener("click", secondAction); // Both will run!
removeEventListener()
Dynamically detaches a previously attached listener. Crucial: The function reference passed to removeEventListener must be the exact same function used in addEventListener. Anonymous functions cannot be removed directly.
// ✅ Correct: Named function
function showAlert() { alert("Hello"); }
btn.addEventListener("click", showAlert);
btn.removeEventListener("click", showAlert);
// ❌ Incorrect: Anonymous functions are unique instances
btn.addEventListener("click", function() { alert("Hello"); });
// btn.removeEventListener("click", function() { alert("Hello"); }); // Won't work!
Event Propagation
When nested elements have event listeners, the browser must decide the execution order. This is called event propagation.
| Mode | Order of Execution | useCapture Value |
|---|---|---|
| Bubbling (Default) | Innermost element → Outermost parent | false |
| Capturing | Outermost parent → Innermost element | true |
Example
<div id="outer">
<p id="inner">Click me</p>
</div>
- If
<p>is clicked with bubbling:<p>handler runs first, then<div>handler. - If
<p>is clicked with capturing:<div>handler runs first, then<p>handler.
Best Practices & Common Pitfalls
| Pitfall | Best Practice |
|---|---|
Using inline onclick in modern projects | Use addEventListener() for separation of concerns |
| Attaching listeners inside loops without caching | Cache elements: const btn = document.getElementById("x"); then attach once |
| Forgetting event type strings must be lowercase | Use "click" not "Click" or "onclick" |
Passing anonymous functions to removeEventListener | Always use named functions or store references if removal is needed |
Ignoring preventDefault() on form/button clicks | Use event.preventDefault() to stop default browser actions when needed |
Quick Guide
// 🔗 Add Listener
el.addEventListener("click", myFunction);
// 🗑️ Remove Listener
el.removeEventListener("click", myFunction);
// 🌊 Control Propagation
el.addEventListener("click", myFunction, false); // Bubbling (default)
el.addEventListener("click", myFunction, true); // Capturing
// 📦 Anonymous function with parameters
el.addEventListener("click", function() { myCustomFunc(a, b); });
// 🛑 Stop default behavior (e.g., form submission, link navigation)
el.addEventListener("submit", function(e) { e.preventDefault(); });
Suggestion
Alert
Question 1
Problem Statement
Design an HTML page as shown in figure(refer to lab manual). Implement the event "on button click display data" using HTML DOM events.
Before click on submit button:
Figure 1: Text with button but no time text
After click on submit button:
Figure 2: Show Date & Time below submit button
Preview (Working)
Exercise 1: Display Date on Click
Click the button to display the date
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex1: Display Date</title>
</head>
<body style="font-family: sans-serif; padding: 20px">
<h2>Exercise 1: Display Date on Click</h2>
<button id="showDateBtn">Show Date</button>
<p id="dateOutput" style="margin-top: 10px; font-weight: bold"></p>
<script>
// Attach event listener using addEventListener (Session 5 concept)
document
.getElementById("showDateBtn")
.addEventListener("click", () => {
const today = new Date().toLocaleDateString();
document.getElementById("dateOutput").textContent =
`Today's Date: ${today}`;
});
</script>
</body>
</html>
Question 2
Problem Statement
Design an HTML page to shown that, when this page is loaded it must check the cookies status of the user's browser and dispay a message accordingly in the popup box i.e if cookies are enabled show: "Cookies are enabled" and if not then show: "Cookies are disabled". Implement the event "on load" using HTML DOM events
Preview (Working)
Exercise 2: Cookie Status
Initializing...
Alert shown when scrolled to this section, Only once.
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex2: Cookie Status Check</title>
</head>
<body style="font-family: sans-serif; padding: 20px">
<h2>Exercise 2: Cookie Status on Load</h2>
<p>Reload the page to trigger the load event.</p>
<script>
// Using window.onload as specified in the lab
window.addEventListener("load", () => {
if (navigator.cookieEnabled) {
alert("Cookies are enabled");
} else {
alert("Cookies are disabled");
}
});
</script>
</body>
</html>
Question 3
Problem Statement
Whenever user input a text in the text box in any case (i.e. upper or lower case), automatically it should be converted to uppercase. Design an HTML page to implement above functionality using HTML DOM event "onchange".
Preview (Working)
Exercise 3: Auto Uppercase
Converted: Waiting for input...
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex3: Auto Uppercase</title>
</head>
<body style="font-family: sans-serif; padding: 20px">
<h2>Exercise 3: Auto Uppercase on Change</h2>
<input
type="text"
id="textInput"
placeholder="Type something (press Enter or click outside)"
style="padding: 8px; width: 300px"
/>
<p id="result" style="margin-top: 10px; font-weight: bold"></p>
<script>
document
.getElementById("textInput")
.addEventListener("change", function () {
// Convert to uppercase and update value
this.value = this.value.toUpperCase();
document.getElementById("result").textContent =
`Converted: ${this.value}`;
});
</script>
</body>
</html>
Question 4
Problem Statement
Design HTML page to implement HTML DOM events by changing an image on the following events: onmouseover, onmouseout, onmousedown, and onmouseup Events.
Preview (Working)
Exercise 4: Image Mouse Events
Hover or click the image
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ex4: Mouse Events on Image</title>
</head>
<body style="font-family: sans-serif; padding: 20px; text-align: center">
<h2>Exercise 4: Image Mouse Events</h2>
<img
id="dynamicImg"
src="https://placehold.co/200x200/cccccc/333?text=Default"
alt="Event Target"
style="border: 2px solid #333; margin: 20px 0"
/>
<p id="eventLog" style="font-style: italic; color: #555">
Hover or click the image
</p>
<script>
const img = document.getElementById("dynamicImg");
const log = document.getElementById("eventLog");
img.addEventListener("mouseover", () => {
img.src =
"https://placehold.co/200x200/3498db/fff?text=Mouse+Over";
log.textContent = "Event: mouseover";
});
img.addEventListener("mouseout", () => {
img.src =
"https://placehold.co/200x200/95a5a6/fff?text=Mouse+Out";
log.textContent = "Event: mouseout";
});
img.addEventListener("mousedown", () => {
img.src =
"https://placehold.co/200x200/e74c3c/fff?text=Mouse+Down";
log.textContent = "Event: mousedown";
});
img.addEventListener("mouseup", () => {
img.src =
"https://placehold.co/200x200/2ecc71/fff?text=Mouse+Up";
log.textContent = "Event: mouseup";
});
</script>
</body>
</html>