Introduction and Actualization

Hello, and welcome to our exciting exploration of JavaScript's advanced event handling! Today, we'll discover how to manage webpage events proficiently. Specifically, we will look at Event Bubbling, stopPropagation, Event Delegation, and how to create and dispatch custom events.

Before we dive into these advanced topics, let's begin with a basic understanding of event handling in JavaScript.

Basics: What Are Events?

In JavaScript, an event signals that something has happened on the webpage. This 'something' could be various user actions like a mouse click, movement of the mouse, pressing a key, etc., or it might be browser actions like page loading or a form submission.

Event handling refers to the process of setting up a function (an event handler) that runs when an event occurs. Here is a simple example for illustration:

<button id="myButton">Click Me!</button>

<script>
document.getElementById("myButton").onclick = function() { 
    alert('Button Pressed!'); 
};
</script>

In this example, clicking the button element triggers the onclick event, which runs the function to display an alert message.

Event Bubbling and stopPropagation

Just like popping balloons at a 'party', Event Bubbling happens when an event propagates from an element up to its parent elements. Here's an example using a button nested inside a div:

<div id="parent">
    <button id="child">Click Me!</button>
</div>

<script>
// Assign event to parent
document.getElementById("parent").onclick = function() {
    alert('Div clicked!');
};
// Assign event to child
document.getElementById("child").onclick = function() {
    alert('Button clicked!');
};
</script>

In this example, clicking the child button will first trigger the button's alert, then bubble up to the div, triggering the div's alert.

Sometimes we may want to stop the event from bubbling up. We can do this using the stopPropagation method:

document.getElementById("child").onclick = function(event) {
    // Stop event from bubbling
    event.stopPropagation();
    alert('Button clicked!');
};

This time, clicking the button will trigger the button's alert, but the event will not bubble up to the div, so we will not see the div's alert.

Event Delegation
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal