Skip to main content

JavaScript Events: Bubbling, Capturing, and Propagation

A basic example of a JavaScript event

Events, in JavaScript, are occurrences that can trigger certain functionality, and can result in certain behaviour. A common example of an event, is a “click”, or a “hover”. You can set listeners to watch for these events that will trigger your desired functionality.

What is “propagation”?

Propagation refers to how events travel through the Document Object Model (DOM) tree. The DOM tree is the structure which contains parent/child/sibling elements in relation to each other. You can think of propagation as electricity running through a wire, until it reaches its destination. The event needs to pass through every node on the DOM until it reaches the end, or if it is forcibly stopped.

Event Bubbling and Capturing

Bubbling and Capturing are the two phases of propagation. In their simplest definitions, bubblingtravels from the target to the root, and capturing travels from the root to the target. However, that doesn’t make much sense without first defining what a target and a root is.

The target is the DOM node on which you click, or trigger with any other event.

For example, a button with a click event would be the event target.

The root is the highest-level parent of the target. This is usually the document, which is a parent of the , which is a (possibly distant) parent of your target element.

Capturing is not used nearly as commonly as bubbling, so our examples will revolve around the bubbling phase. As an option though, EventTarget.addEventListener() has an optional third parameter - which takes its argument as a boolean - which controls the phase of the propagation. The parameter is called useCapture, and passing true will cause the listener to be on the capturing phase. The default is false, which will apply it to the bubbling phase.

Once you trigger the event, it will propagate up to the root, and it will trigger every single event handler which is associated with the same type. For example, if your button has a click event, during the bubbling phase, it will bubble up to the root, and trigger every click event along the way.

This kind of behaviour might not sound desirable - and it often isn’t - but there’s an easy workaround...

Event.stopPropagation()

These two methods are used for solving the previously mentioned problem regarding event propagation. Calling Event.stopPropagation() will prevent further propagation through the DOM tree, and only run the event handler from which it was called.

<!--Try it-->
function first() {
  console.log(1);
}
function second() {
  console.log(2);
}
var button = document.getElementById("button");
var container = document.getElementById("container");
button.addEventListener("click", first);
container.addEventListener("click", second);

In this example, clicking the button will cause the console to print 1, 2. If we wanted to modify this so that only the button’s click event is triggered, we could use Event.stopPropagation() to immediately stop the event from bubbling to its parent.

function first(event) {
  event.stopPropagation();
  console.log(1);
}

This modification will allow the console to print 1, but it will end the event chain right away, preventing it from reaching 2.

How does this differ from Event.stopImmediatePropagation()? When would you use either?

<!--Try it-->
function first(event) {
  console.log(1);
}
function second() {
  console.log(2);
}
function third() {
  console.log(3);
}
var button = document.getElementById("button");
var container = document.getElementById("container");
button.addEventListener("click", first);
button.addEventListener("click", second);
container.addEventListener("click", third);

Let’s suppose we wanted to add a third function, which prints 3 to the console. In this scenario, we will also move the second function to also be on the button. We will apply third to the container now.

Long story short: we have two event handlers on the button, and clicking <div#container> will now print 3.

What will happen now? This will behave the same as before, and it will propagate through the DOM tree, and print 1, 2, 3, in that order.

How does this tie in to Event.stopPropagation() and Event.stopImmediatePropagation()?

Adding Event.stopPropagation() to the first function, like so, will print 1, 2 to the console.

function first(event) {
  event.stopPropagation();
  console.log(1);
}

This is because Event.stopPropagation() will immediately prevent all click events on the parent from being triggered, but it does not stop any other event handlers from being called.

As you can see in our example, our button has two click handlers, and it did stop the propagation to its parents. If you wanted to stop all event handlers after the first, that’s whereEvent.stopImmediatePropagation() comes in.

function first(event) {
  event.stopImmediatePropagation();
  console.log(1);
}

Now, the first function really will stop the parent click handlers, and all other click handlers. The console will now print just 1, whereas if we simply used Event.stopPropagation(), it would print 1, 2, and not including either would print 1, 2, 3 .

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...