Home Web Front-end JS Tutorial Event Flow: Bubbling & Capturing

Event Flow: Bubbling & Capturing

Jan 09, 2025 am 06:42 AM

This is post #7 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider joining Frontend Camp ?.


Event bubbling and capturing, both are propagation mechanisms in DOM(Document Object Model). Both these mechanisms are opposite of each other.

Event Bubbling

In Event bubbling, the event, after triggering the handler on the target element(event.target) propagates upwards(bubbles) to the root element of the document. On its way it triggers all the event handlers on the parent elements.

/*
<div>



<p>In the snippet above, when you click the button you'll see the following output in console:<br>
</p>

<pre class="brush:php;toolbar:false">"Button handler"
"Container handler"
Copy after login

First the handler on the button is called and the event.target property is set to button as it initiated the event. Event on its way up to the root element, it calls its parent's event handler.

Almost all events bubble but there are a few exceptions like focus event that do not bubble.

You can stop bubbling by calling the stopPropagation() method on the event. If the button's event handler in the above snippet stops propagation, the container's event handler won't be called.

btn.addEventListener('click', function(event) {
  console.log('Button handler!');

  // ancestor elements won't receive the event
  event.stopPropagation();
});
Copy after login

You can access the element that initiated the event by accessing target.event property. Also, the element whose handler is being executed can be accessed using event.currentTarget.

container.addEventListener('click', function(event) {
  console.log('Container handler!'); // 'Container handler!'
  console.log(event.target); // btn
  console.log(event.currentTarget); // container
  console.log(this); // container
});
Copy after login

Want to learn more about the this keyword? I wrote a post on it.

Event Capturing

We've only been seeing half the picture until now. When the button in the above snippet is clicked, it isn't the first element to receive that event. ?

The event flow consists of three phases:

  1. Capturing phase: The event flows from the root element to the target element.
  2. Target phase: The event is received on the target element.
  3. Bubbling phase: The event starts propagating back to the root element.

Event Flow: Bubbling & Capturing

By default, all event handlers are only called during target and bubbling phase. To call event handlers in the capturing phase, pass true as the third argument.

el.addEventListener('click', () => {}, true);
// or to be more explicit
el.addEventListener('click', () => {}, { capture: true });
Copy after login

If you are using a handler in capturing phase, it won't be called in the bubbling phase.

Similar to bubbling, when event.stopPropagation() is called during the capturing phase it won't let the event flow further i.e. down the DOM, in this case.

In the snippet we discussed earlier, if container stops propagation during capturing phase, the button's handler will never be called.

/*
<div>



<p>This is why you should always have a good reason to use event.stopPropagation(). It can lead to unexpected issues that are hard to debug in a complex or deeply nested DOM tree.</p><p>Event capturing is rarely used compared to Bubbling. Bubbling has a lot of use cases like "Event delegation" - an important performance pattern.</p>

<p>This post lays down the foundation for the next topic - Event delegation. Make sure you understand it well. Have doubts? Leave them in the comments. ✌️</p>


<hr>

<h2>
  
  
  Summary
</h2>

<ol>
<li>Event flow consists of three phases: Capturing, Target and Bubbling phase.</li>
<li>In the capturing phase, event flows down from the root element to the target(event.target) element.</li>
<li>In the bubbling phase, event flows from the target element to the root element.</li>
<li>By default, all event handlers are called only during target and bubbling phase.</li>
<li>By passing a third argument in the addEventListener function, you can set the handler on the capturing phase.</li>
<li>At any point in the event flow, calling event.stopPropagation() will stop the event from flowing further.</li>
</ol>


<hr>

<p>Like what you just read? ? Consider joining the waitlist on Frontend Camp.</p>

<p>Leave some reactions "?" and comments so this post helps other devs like you. ?</p>


          

            
  

            
        
Copy after login

The above is the detailed content of Event Flow: Bubbling & Capturing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles