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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...