JavaScript Events and Event Bubbling | Lecture 38 - BLOG PK
Skip to content

JavaScript Events and Event Bubbling | Lecture 38

JavaScript Events and Event Bubbling

Let’s begin with Lecture 38 of the HTML5 & CSS3 series. JavaScript Events and Event Bubbling – Understanding How Interaction Works. This lecture is for absolute beginners; even kids can follow along and understand.

🎯 Objective:

By the end of this lecture, you will:

  • Understand what JavaScript events are and how they work
  • Learn about event bubbling and event capturing
  • Be able to control event propagation using stopPropagation()
  • Know how to use addEventListener() for flexible event handling
  • Build a real example that shows how events flow through HTML elements

πŸ–±οΈ What Are JavaScript Events?

Events happen when users interact with your webpage β€” like clicking a button, typing in a box, or submitting a form.

Think of it like this:

If your website was a playground, then events are all the things kids do β€” running, jumping, sliding β€” and JavaScript helps respond to those actions!

Some common events:

  • click – When a user clicks an element
  • mouseover / mouseout – When the mouse enters or leaves an element
  • keydown / keyup – When a key is pressed or released
  • submit – When a form is submitted
  • change – When the value of an input changes

πŸ” What Is Event Bubbling?

Event bubbling means that when an event happens on a child element, it also triggers on its parent elements β€” like ripples in water.

Think of it like this:

Imagine knocking on a small box inside a bigger box. The knock is felt not just by the small box but also by the big one around it β€” that’s event bubbling !

Example:
<div onclick="alert('Div clicked')">
    <button onclick="alert('Button clicked')">Click Me</button>
</div>

When you click the button:

  1. Button alert shows first
  2. Then div alert shows second (because of bubbling)

⬇️ What Is Event Capturing?

Event capturing is the opposite of bubbling β€” the event starts at the top (window) and goes down to the target element.

It’s less commonly used, but sometimes useful for advanced applications.

To use capturing, set the third argument in addEventListener() to true.

🚫 Stop Propagation – Control Where the Ripple Goes

If you don’t want the event to bubble up, use event.stopPropagation().

Example:
document.querySelector("button").addEventListener("click", function(event) {
    alert("Button clicked!");
    event.stopPropagation(); // Stops the div from getting the event
});

Now clicking the button won’t trigger the div’s click handler!

πŸ’» Try This: Explore Event Bubbling in Action

Let’s build a simple page that shows how events travel from child to parent.

Step 1: Create a New File

In your VS Code project folder (MyFirstWebsite), create a new file named:

event-bubbling.html
Step 2: Add This Code
<!DOCTYPE html>
<html>
<head>
    <title>Event Bubbling</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 40px;
        }

        .container {
            padding: 20px;
            background-color: #f0f0f0;
            border: 2px solid #ccc;
        }

        .card {
            padding: 15px;
            background-color: #fff;
            border: 1px solid #999;
            margin-top: 20px;
        }

        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <h2>Event Bubbling Demo</h2>

    <div class="container" onclick="handleContainer()">
        Container (Outer Box)

        <div class="card" onclick="handleCard(event)">
            Card (Middle Box)

            <button class="btn" onclick="handleButton(event)">Click Me</button>

        </div>

    </div>

    <p id="log"></p>

    <script>
        function handleContainer() {
            document.getElementById("log").textContent = "Container clicked!";
        }

        function handleCard(event) {
            document.getElementById("log").textContent += "\nCard clicked!";
        }

        function handleButton(event) {
            document.getElementById("log").textContent += "\nButton clicked!";
            // event.stopPropagation(); // Uncomment to stop bubbling
        }
    </script>

</body>
</html>
Step 3: Run with Live Server

Right-click the code β†’ Show All Commands β†’ Launch Live Server

πŸŽ‰ Now every time you click the button, you’ll see how the event bubbles up through the card and container!

Try uncommenting event.stopPropagation() in handleButton() and see what happens.

πŸ’‘ Bonus: Use addEventListener() for Better Control

Instead of inline onclick, we can use addEventListener() β€” which gives more flexibility.

Update Your Script Like This:
<script>
    document.querySelector(".container").addEventListener("click", function() {
        console.log("Container clicked");
    });

    document.querySelector(".card").addEventListener("click", function(event) {
        console.log("Card clicked");
    });

    document.querySelector(".btn").addEventListener("click", function(event) {
        console.log("Button clicked");
        // event.stopPropagation();
    });
</script>

This way, you can add multiple listeners and better manage event behavior.

JavaScript Events and Event Bubbling
JavaScript Events and Event Bubbling
πŸ’‘ Bonus: Event Delegation – Handle Events Efficiently

Sometimes, you have many buttons or dynamic content.
Instead of adding listeners to each, you can listen on the parent and check which child was clicked.

Example: Dynamic List

Add this HTML:

<h2>Dynamic List Click</h2>
<ul id="dynamicList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Add this JavaScript:

<script>
    document.getElementById("dynamicList").addEventListener("click", function(event) {
        if (event.target.tagName === "LI") {
            alert("You clicked: " + event.target.textContent);
        }
    });
</script>

Now clicking any list item shows a message β€” even if items are added dynamically later!

πŸ§ͺ Try It Yourself!

  1. Add a new <li> item via JavaScript and test if it still works with event delegation.
  2. Make the card show a different message if the button was clicked vs directly clicked.
  3. Use event.target vs this to explore differences in event handling.
  4. Add a β€œRemove” button to each list item and remove it using removeChild() when clicked.
βœ… Summary of What You Learned Today
CONCEPTCODE EXAMPLE
Event BubblingClicking child triggers parent events too
Stop Propagationevent.stopPropagation() stops event from going up
Event Listenerelement.addEventListener("click", function() { ... })
Event Targetevent.target tells which element was clicked
Event DelegationListen on parent to manage child events
Capturing vs BubblingUse { capture: true } to listen during capturing phase

πŸš€ Next Lecture Preview:

In Lecture 39 , we’ll learn how to build a to-do list app using everything we’ve learned so far β€” including arrays, DOM manipulation, localStorage, and event handling β€” making it fully functional and persistent across sessions!

Stay Updated

If you found this information useful, don’t forget to bookmark this page and Share.

HTML5 and CSS3 Compleate Series

Najeeb Alam

Najeeb Alam

Technical writer specializes in developer, Blogging and Online Journalism. I have been working in this field for the last 20 years.