搜索
首页web前端js教程Event Bubbling and Capturing - Learn like you are 5

Event Bubbling and Capturing - Learn like you are 5

Come on, 'Learn like you're 5' is just a phrase — I'm not telling a toy story here! But I promise, if you read through carefully from start to finish, it'll all make sense.

Event bubbling and capturing are two phases of how events propagate (or travel) through the DOM (Document Object Model) when an event is triggered in JavaScript. Now, this statement requires to clear out the concept of event propagation.

Event Propagation

When an event occurs on an element, like a button inside a div, the event doesn't just happen at that button. The event travels through the DOM in a process known as event propagation. This process happens in two main phases:

  • Event Capturing (also called "trickling")

  • Event Bubbling

Now, I hope you got the idea. Let's understand both with examples.

Event Bubbling

Event bubbling means that when an event occurs on an element, it first triggers the event handler for that element. Then, it moves upward in the DOM tree to trigger the event handlers of its parent elements, and so on, until it reaches the document or the root of the DOM tree.

<div id="parent" style="padding: 20px; background-color: lightblue;">
  Parent Div
  <button id="child">Click Me!</button>
</div>

<script>
  document.getElementById('parent').addEventListener('click', function() {
    alert('Parent Div Clicked!');
  });

  document.getElementById('child').addEventListener('click', function(event) {
    alert('Button Clicked!');
    // event.stopPropagation(); // If you want to stop bubbling, uncomment this line
  });
</script>

Example Explanation: When you click the button, the "Button Clicked!" alert shows first because the event is triggered on the button. After that, the event "bubbles" up to the parent div, and you see the "Parent Div Clicked!" alert. This is because the event starts at the button and then goes up to its parent div. So, this process of propagation is called ‘Event Bubbling’.

Event Capturing

Event capturing is the reverse of bubbling. The event starts from the top of the webpage (beginning with the document) and moves down toward the element you interacted with. This means the event handlers for parent elements will be triggered first, and the event will move down to the child element you clicked or interacted with.

<div id="parent" style="padding: 20px; background-color: lightgreen;">
  Parent Div
  <button id="child">Click Me!</button>
</div>

<script>
  document.getElementById('parent').addEventListener('click', function() {
    alert('Parent Div Clicked!');
  }, true); // 'true' makes this event handler run during the capturing phase

  document.getElementById('child').addEventListener('click', function() {
    alert('Button Clicked!');
  });
</script>

In this case, when you click the button, the "Parent Div Clicked!" alert will show first. Then, the "Button Clicked!" alert will show because the event starts from the document level, captures (trickles) down to the parent div first, and then reaches the button.

The value true of the third argument of addEventListener is the determiner of capturing phase.

Every Event Goes Through 3 Phases

Naturally, every event goes through all three phases:

  • Capturing phase: The event starts at the top (document) and travels down to the target.

  • Target phase: The event reaches the element you interacted with (the target).

  • Bubbling phase: After reaching the target, the event bubbles back up through the parent elements.

So yes, an event naturally moves through all three phases, but JavaScript gives you control over which phase your event listener will act in.

Even though events go through all three phases, JavaScript’s event listeners are by default attached to the bubbling phase. This means when you add an event listener without specifying anything, it will listen for the event only in the bubbling phase (after the event has reached the target and starts moving up).

When you pass true as the third argument, you tell JavaScript to listen for the event during the capturing phase (as it travels down the DOM). The event still goes through all phases (capturing, target, and bubbling), but the listener will be triggered during the capturing phase, before the event reaches the target element.

Does the event go from capturing to bubbling when you use true? No, the event always moves through both capturing and bubbling. When you pass true, you’re not preventing the bubbling phase. You’re just telling the listener to respond during capturing. The event will continue from capturing to target and then bubbling as usual.

Summary:

  • All events naturally go through capturing, target, and bubbling phases.

  • By default, event listeners work during the bubbling phase (after the event reaches the target and moves upward).

  • When you pass true, you’re telling the event listener to trigger during the capturing phase (as the event travels downward).

  • The event still goes through all phases (capturing, target, and bubbling), but your listener decides in which phase to act.

以上是Event Bubbling and Capturing - Learn like you are 5的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript引擎:比较实施JavaScript引擎:比较实施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

超越浏览器:现实世界中的JavaScript超越浏览器:现实世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在现实世界中的应用包括服务器端编程、移动应用开发和物联网控制:1.通过Node.js实现服务器端编程,适用于高并发请求处理。2.通过ReactNative进行移动应用开发,支持跨平台部署。3.通过Johnny-Five库用于物联网设备控制,适用于硬件交互。

使用Next.js(后端集成)构建多租户SaaS应用程序使用Next.js(后端集成)构建多租户SaaS应用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技术工具构建了功能性的多租户SaaS应用程序(一个Edtech应用程序),您可以做同样的事情。 首先,什么是多租户SaaS应用程序? 多租户SaaS应用程序可让您从唱歌中为多个客户提供服务

如何使用Next.js(前端集成)构建多租户SaaS应用程序如何使用Next.js(前端集成)构建多租户SaaS应用程序Apr 11, 2025 am 08:22 AM

本文展示了与许可证确保的后端的前端集成,并使用Next.js构建功能性Edtech SaaS应用程序。 前端获取用户权限以控制UI的可见性并确保API要求遵守角色库

JavaScript:探索网络语言的多功能性JavaScript:探索网络语言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是现代Web开发的核心语言,因其多样性和灵活性而广泛应用。1)前端开发:通过DOM操作和现代框架(如React、Vue.js、Angular)构建动态网页和单页面应用。2)服务器端开发:Node.js利用非阻塞I/O模型处理高并发和实时应用。3)移动和桌面应用开发:通过ReactNative和Electron实现跨平台开发,提高开发效率。

JavaScript的演变:当前的趋势和未来前景JavaScript的演变:当前的趋势和未来前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

神秘的JavaScript:它的作用以及为什么重要神秘的JavaScript:它的作用以及为什么重要Apr 09, 2025 am 12:07 AM

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

Python还是JavaScript更好?Python还是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。 1.Python以简洁语法和丰富库生态着称,适用于数据分析和Web开发。 2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。