Topic 45 of 48 · Full Stack Essentials

JavaScript Events

Lesson TL;DRTopic 8: JavaScript Events 📖 15 min read · 🎯 advanced · 🧭 Prerequisites: sessionsloginpagelogoutsessiondestroytimeoutcookiesintroductionpageredirect, tagslist Why this matters You've built pages th...
15 min read·advanced·javascript · events · event-listeners · dom

Topic 8: JavaScript Events

📖 15 min read · 🎯 advanced · 🧭 Prerequisites: sessions-login-page-logout-session-destroy-timeoutcookies-introduction-page-redirect, tags-list

Why this matters

You've built pages that look decent — headings, buttons, maybe a form. But when you click that button? Nothing happens. It just sits there. That's the gap JavaScript Events fills. Events are how your page listens — for a click, a keypress, a form submit, a mouse hover. The moment you wire up your first event listener, your page stops being a poster and starts being a program. This lesson is where your JavaScript finally feels alive.

What You'll Learn

  • Understand what JavaScript events are and what triggers them
  • Attach and remove event listeners using addEventListener and removeEventListener
  • Work with the most common event types: click, mouseover, mouseout, and keydown
  • Inspect the event object to read runtime data like event.type, event.key, and event.target
  • Apply event delegation to handle multiple child elements with a single parent listener

The Analogy

Think of your web page as Vizag's town hall, and JavaScript events as the building's intercom system. Every door, button, and microphone in the hall is wired to a central switchboard — the browser's event system. When a citizen (the user) presses a doorbell (click), speaks into a microphone (keydown), or steps into a room (mouseover), the switchboard lights up and routes the signal to the right handler function. Without the intercom wired up, citizens can knock all day and nothing happens. With it active, every interaction triggers an immediate, purposeful response. addEventListener is the act of wiring a specific button to a specific response — and removeEventListener is unplugging it when you no longer need it.

Chapter 1: What Are JavaScript Events?

the trainer opened with the core definition: JavaScript events are actions or occurrences that happen in the browser and can be detected — and responded to — by JavaScript code. They are the foundation of interactivity on the web.

Events can be triggered by a wide range of actions, including:

  • Clicking a button
  • Hovering over an element
  • Submitting a form
  • Pressing a key
  • Loading a web page

Every one of these moments is an opportunity to run code. The browser fires an event; your JavaScript catches it and decides what to do next.

Chapter 2: Event Handling

We learned that handling an event requires two pieces working together:

  • Event listener — watches an element and waits for a specific event to occur
  • Event handler — a function that executes when that event fires

Adding Event Listeners

The standard way to attach an event listener is the addEventListener method, called on any DOM element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Handling Example</title>
</head>
<body>
    <h1>Welcome to Vizag</h1>
    <button id="greetButton">Click Me</button>

    <script>
        // Select the button element
        const button = document.getElementById('greetButton');

        // Add an event listener to the button
        button.addEventListener('click', function() {
            alert('Hello, Vizag!');
        });
    </script>
</body>
</html>

addEventListener takes two required arguments: the event name as a string (e.g., 'click') and the handler function to call when that event fires. The handler receives an event object automatically — more on that in Chapter 4.

Chapter 3: Common Event Types

the trainer walked the class through the most frequently used event types in everyday web development.

The click Event

Fires when an element is clicked (mouse button pressed and released on the element).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Click Event Example</title>
</head>
<body>
    <button id="clickButton">Click Me</button>

    <script>
        const clickButton = document.getElementById('clickButton');

        clickButton.addEventListener('click', function() {
            console.log('Button was clicked!');
        });
    </script>
</body>
</html>

The mouseover and mouseout Events

mouseover fires when the mouse pointer enters an element; mouseout fires when it leaves. The two are almost always paired to create hover effects in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouseover Event Example</title>
</head>
<body>
    <div id="hoverDiv" style="width: 200px; height: 200px; background-color: lightblue;">
        Hover over me
    </div>

    <script>
        const hoverDiv = document.getElementById('hoverDiv');

        hoverDiv.addEventListener('mouseover', function() {
            hoverDiv.style.backgroundColor = 'lightgreen';
        });

        hoverDiv.addEventListener('mouseout', function() {
            hoverDiv.style.backgroundColor = 'lightblue';
        });
    </script>
</body>
</html>

The keydown Event

Fires every time a key is pressed down. Attach it to an input field (or to document for global key captures) to react in real time as the user types.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keydown Event Example</title>
</head>
<body>
    <input type="text" id="textInput" placeholder="Type something...">

    <script>
        const textInput = document.getElementById('textInput');

        textInput.addEventListener('keydown', function(event) {
            console.log('Key pressed:', event.key);
        });
    </script>
</body>
</html>

Notice event.key — this is the event object in action. The browser passes it automatically into the handler.

Chapter 4: The Event Object

Whenever an event fires, the browser creates an event object and passes it as the first argument to your handler. This object is a gold mine of runtime information about what just happened.

Commonly accessed properties:

PropertyWhat it contains
event.typeThe name of the event ("click", "keydown", etc.)
event.targetThe DOM element that triggered the event
event.target.textContentThe visible text of the element that was clicked
event.keyThe key name when a keyboard event fires
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Object Example</title>
</head>
<body>
    <button id="eventButton">Click Me</button>

    <script>
        const eventButton = document.getElementById('eventButton');

        eventButton.addEventListener('click', function(event) {
            console.log('Event type:', event.type);
            console.log('Button text:', event.target.textContent);
        });
    </script>
</body>
</html>

Running this and clicking the button will log:

Event type: click
Button text: Click Me

event.target always refers to the element the user actually interacted with — crucial for event delegation (Chapter 6).

Chapter 5: Removing Event Listeners

Sometimes a listener should fire only once and then be cleaned up. The removeEventListener method detaches a previously attached handler. The critical requirement: the handler must be a named function — you cannot remove an anonymous function because there is no reference to it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Remove Event Listener Example</title>
</head>
<body>
    <button id="removeButton">Click Me</button>

    <script>
        const removeButton = document.getElementById('removeButton');

        function handleClick() {
            alert('Button was clicked!');
            removeButton.removeEventListener('click', handleClick);
        }

        removeButton.addEventListener('click', handleClick);
    </script>
</body>
</html>

After the first click, handleClick removes itself. The alert fires exactly once, and all subsequent clicks are silently ignored. This pattern is essential for one-time confirmations, tutorial tooltips, and any interaction that should only happen once per session.

Chapter 6: Event Delegation

the trainer saved the most powerful pattern for last. Event delegation is a technique where instead of attaching a listener to each child element individually, you attach a single listener to a common parent and let events bubble up from the children.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Delegation Example</title>
</head>
<body>
    <ul id="itemList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>

    <script>
        const itemList = document.getElementById('itemList');

        itemList.addEventListener('click', function(event) {
            if (event.target.tagName === 'LI') {
                console.log('List item clicked:', event.target.textContent);
            }
        });
    </script>
</body>
</html>

One listener on #itemList covers all three <li> children — and any new items dynamically added to the list later. The handler checks event.target.tagName === 'LI' to confirm a list item (not the <ul> itself) was clicked before acting. Benefits:

  • Performance — one listener instead of N listeners
  • Dynamic content — works for items added after the page loads
  • Cleaner teardown — remove one listener, not N
flowchart TD
    A[User clicks Item 2] --> B[click event fires on LI]
    B --> C[Event bubbles up to UL#itemList]
    C --> D{event.target.tagName === 'LI'?}
    D -- Yes --> E[Log: List item clicked: Item 2]
    D -- No --> F[Ignore — UL itself was clicked]

🧪 Try It Yourself

Task: Build an interactive color-switcher panel.

Create an HTML page with five <div> elements, each containing a color name (Red, Green, Blue, Yellow, Purple). Use event delegation on a single parent container so that clicking any div sets the page's background-color to that color.

Success criterion: Clicking "Blue" turns the entire page background blue; clicking "Red" turns it red — with no individual listeners on the divs.

Starter snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Color Switcher</title>
    <style>
        .swatch {
            width: 150px;
            padding: 12px;
            margin: 8px;
            text-align: center;
            cursor: pointer;
            border: 2px solid #333;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div id="palette">
        <div class="swatch" data-color="red">Red</div>
        <div class="swatch" data-color="green">Green</div>
        <div class="swatch" data-color="blue">Blue</div>
        <div class="swatch" data-color="yellow">Yellow</div>
        <div class="swatch" data-color="purple">Purple</div>
    </div>

    <script>
        const palette = document.getElementById('palette');

        palette.addEventListener('click', function(event) {
            // YOUR CODE HERE
            // Hint: use event.target.dataset.color
        });
    </script>
</body>
</html>

🔍 Checkpoint Quiz

Q1. What does addEventListener return, and why does that matter when you later want to remove the listener?

Q2. Given this code, what is logged to the console when the user types the letter A into the input?

<input type="text" id="box" placeholder="Type here">
<script>
    document.getElementById('box').addEventListener('keydown', function(e) {
        console.log(e.key.toUpperCase() + ' pressed');
    });
</script>

A) a pressed B) A pressed C) KeyA pressed D) undefined pressed

Q3. The following event delegation snippet has a subtle bug. What is it?

document.getElementById('menu').addEventListener('click', function(event) {
    console.log('Item clicked:', event.target.textContent);
});

A) addEventListener is called incorrectly — it should be attachEvent B) event.target could be the #menu container itself, not just the child items — there is no tag or class guard C) textContent does not exist on event targets D) The listener should be on document, not on #menu

Q4. You have a "Confirm Delete" button that should show an alert exactly once and then become inert. Write the JavaScript to achieve this using removeEventListener. What is the key requirement for this approach to work?

A1. addEventListener returns undefined — it doesn't give you back a reference. This is why you must hold a reference to the handler function in a named variable or function declaration before calling addEventListener; that same reference is required by removeEventListener to identify and detach the exact listener.

A2. B) A pressede.key returns "a" (lowercase), then .toUpperCase() converts it to "A", so the output is A pressed.

A3. B) Without a guard (like if (event.target.tagName === 'LI')), clicking the #menu container's padding or gap area will fire the handler with event.target pointing to the container itself, logging its full concatenated text content rather than a single item.

A4. Declare the handler as a named function, add the listener, and inside the handler call removeEventListener with that same named function reference. The key requirement is the named function reference — anonymous functions cannot be removed because there is no way to pass the same reference back to removeEventListener.

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

function confirmOnce() {
    alert('Deleted!');
    deleteBtn.removeEventListener('click', confirmOnce);
}

deleteBtn.addEventListener('click', confirmOnce);

🪞 Recap

  • JavaScript events are browser-detected actions (clicks, key presses, mouse movement, form submissions) that trigger JavaScript code.
  • addEventListener(eventName, handler) wires a function to fire whenever that event occurs on a given element.
  • The event object passed automatically to every handler carries runtime data: event.type, event.target, event.key, and more.
  • removeEventListener detaches a handler — but only works with named functions, not anonymous ones.
  • Event delegation places one listener on a parent element and uses event.target to identify which child triggered the event, improving performance and supporting dynamically added elements.

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.