Skip to content

Session 5

JavaScript HTML DOM Events and Event Listener

Updated View as Markdown

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

Do not copy. Read for understanding and the viva
  • Understand common HTML DOM events and their triggers
  • Attach event handlers using addEventListener() without overwriting existing ones
  • Control event propagation using the useCapture parameter (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 CategoryCommon ExamplesTrigger
Mouseclick, dblclick, mouseover, mouseout, mousedown, mouseupUser interacts with pointing device
Keyboardkeydown, keyup, keypressUser presses/releases keys
Form/Inputchange, input, submit, focus, blurUser modifies or submits form data
Window/Documentload, DOMContentLoaded, resize, scrollPage lifecycle or viewport changes
Media/Imageload (on <img>), play, pauseResource state changes

Event Handling Evolution

ApproachSyntaxProsCons
Inline HTML<button onclick="myFunc()">Quick to writeMixes HTML & JS, hard to maintain, overwrites if duplicated
DOM Propertybtn.onclick = myFunc;Simple separationOnly allows one handler per event type (overwrites previous)
Event Listenerbtn.addEventListener("click", myFunc);Recommended: supports multiple handlers, clean separation, modern standardSlightly more verbose

Syntax & Parameters

addEventListener()

element.addEventListener(event, function, useCapture);
ParameterDescription
eventString name of the event (e.g., “click”, “load”, “change”)
functionCallback to execute when event fires (named function or anonymous)
useCaptureOptional 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.

ModeOrder of ExecutionuseCapture Value
Bubbling (Default)Innermost element → Outermost parentfalse
CapturingOutermost parent → Innermost elementtrue

Example

Do not copy. Read for understanding and the viva
<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

Do not copy. Read for understanding and the viva
PitfallBest Practice
Using inline onclick in modern projectsUse addEventListener() for separation of concerns
Attaching listeners inside loops without cachingCache elements: const btn = document.getElementById("x"); then attach once
Forgetting event type strings must be lowercaseUse “click” not “Click” or “onclick”
Passing anonymous functions to removeEventListenerAlways use named functions or store references if removal is needed
Ignoring preventDefault() on form/button clicksUse event.preventDefault() to stop default browser actions when needed

Quick Guide

Do not copy. Read for understanding and the viva
// 🔗 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(); });

Question 1

Problem Statement

Write in lab record

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)

Do not copy. Read for understanding and the viva

Exercise 1: Display Date on Click

Click the button to display the date

Code

Write in lab record
date.htmlhtml
<!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

Write in lab record

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)

Do not copy. Read for understanding and the viva

Exercise 2: Cookie Status

Initializing...

Alert shown when scrolled to this section, Only once.

Code

Write in lab record
color-change.htmlhtml
<!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

Write in lab record

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)

Do not copy. Read for understanding and the viva

Exercise 3: Auto Uppercase

Converted: Waiting for input...

Code

Write in lab record
onchange.htmlhtml
<!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

Write in lab record

Design HTML page to implement HTML DOM events by changing an image on the following events: onmouseover, onmouseout, onmousedown, and onmouseup Events.

Preview (Working)

Do not copy. Read for understanding and the viva

Exercise 4: Image Mouse Events

Hover or click the image

Code

Write in lab record
image-mouse-event.htmlhtml
<!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>
Navigation

Type to search…

↑↓ navigate↵ selectEsc close