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

Event Bubbling and Capturing - Learn like you are 5

Sep 22, 2024 pm 06:32 PM

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
<🎜>掩盖:探险33-如何获得完美的色度催化剂
2 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1676
14
CakePHP 教程
1429
52
Laravel 教程
1333
25
PHP教程
1278
29
C# 教程
1257
24
Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在行动中:现实世界中的示例和项目 JavaScript在行动中:现实世界中的示例和项目 Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

了解JavaScript引擎:实施详细信息 了解JavaScript引擎:实施详细信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:开发环境和工具 Python vs. JavaScript:开发环境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

C/C在JavaScript口译员和编译器中的作用 C/C在JavaScript口译员和编译器中的作用 Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

Python vs. JavaScript:比较用例和应用程序 Python vs. JavaScript:比较用例和应用程序 Apr 21, 2025 am 12:01 AM

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

从网站到应用程序:JavaScript的不同应用 从网站到应用程序:JavaScript的不同应用 Apr 22, 2025 am 12:02 AM

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

See all articles