Blogs
Hiểu về Event Bubbling, Delegation, Propagation và Preventing trong JavaScript

Hiểu về Event Bubbling, Delegation, Propagation và Preventing trong JavaScript

Giải thích chi tiết về cách sự kiện lan truyền trong DOM, cách ủy quyền sự kiện và ngăn chặn hành vi mặc định.

Hiểu về Event Bubbling, Delegation, Propagation và Preventing trong JavaScript

Trong JavaScript, event handling (xử lý sự kiện) là một phần quan trọng giúp tương tác với người dùng. Khi một sự kiện xảy ra, nó không chỉ ảnh hưởng đến phần tử được nhắm đến mà còn có thể lan truyền qua DOM theo nhiều cách khác nhau.

Hôm nay, chúng ta sẽ tìm hiểu về 4 khái niệm quan trọng:

  1. Event Bubbling (Sự kiện nổi bọt)
  2. Event Delegation (Ủy quyền sự kiện)
  3. Event Propagation (Sự lan truyền sự kiện)
  4. Event Preventing (Ngăn chặn sự kiện)

1. Event Bubbling (Sự kiện nổi bọt)

Event Bubbling là gì?
Event Bubbling là quá trình một sự kiện bắt đầu từ phần tử được nhắm đến, sau đó lan truyền lên các phần tử cha trong DOM.

Ví dụ:
Khi bạn nhấp vào một <button> bên trong một <div>, sự kiện click không chỉ kích hoạt trên <button> mà còn lan truyền lên <div> và các phần tử cha khác.

<div id="parent"> <button id="child">Click me</button> </div> <script> document.getElementById("child").addEventListener("click", function () { console.log("Button clicked!"); }); document.getElementById("parent").addEventListener("click", function () { console.log("Div clicked!"); }); </script>

Kết quả:

  • Khi bạn nhấn vào nút, console sẽ in:
Button clicked!
Div clicked!
  • Điều này xảy ra vì sự kiện bắt đầu từ button và nổi bọt lên div.

2. Event Delegation (Ủy quyền sự kiện)

Event Delegation là gì?
Event Delegation là kỹ thuật gắn sự kiện vào phần tử cha thay vì từng phần tử con riêng lẻ.

Tại sao dùng Event Delegation?

  • Giảm số lượng event listener, giúp tối ưu hiệu suất.
  • Hữu ích khi danh sách phần tử thay đổi động (VD: danh sách todo).

Ví dụ:
Thay vì gắn sự kiện vào từng button, ta chỉ gắn vào ul (cha của các li):

<ul id="menu"> <li>Home</li> <li>About</li> <li>Contact</li> </ul> <script> document.getElementById("menu").addEventListener("click", function (event) { if (event.target.tagName === "LI") { console.log("You clicked:", event.target.innerText); } }); </script>

Lợi ích:

  • Nếu sau này thêm <li>, nó vẫn hoạt động mà không cần gắn event listener mới.
  • Giúp code gọn gàng và hiệu quả hơn.

3. Event Propagation (Sự lan truyền sự kiện)

Event Propagation là gì?
Event Propagation là cách sự kiện lan truyền qua cây DOM theo 2 giai đoạn chính:

  1. Capturing Phase (Giai đoạn bắt sự kiện) → Sự kiện đi từ document xuống phần tử mục tiêu.
  2. Bubbling Phase (Giai đoạn nổi bọt) → Sự kiện đi từ phần tử mục tiêu lên document.

Ví dụ:

<div id="outer"> <button id="inner">Click Me</button> </div> <script> document.getElementById("outer").addEventListener( "click", function () { console.log("Div clicked!"); }, true // Bắt sự kiện ở giai đoạn capturing ); document.getElementById("inner").addEventListener( "click", function () { console.log("Button clicked!"); } ); </script>

Kết quả:
Nếu bạn nhấp vào button, thứ tự log sẽ là:

Div clicked!
Button clicked!
  • Vì sự kiện của <div> chạy trước do được đặt ở capturing phase (với true).
  • Nếu không có true, <button> sẽ được xử lý trước vì bubbling phase mặc định.

4. Event Preventing (Ngăn chặn sự kiện)

Event Preventing là gì?
Event Preventing dùng để ngăn chặn hành vi mặc định của trình duyệt, ví dụ:

  • Chặn submit form khi chưa nhập dữ liệu.
  • Chặn link <a> mở trang mới.
  • Chặn click vào checkbox nhưng không muốn thay đổi trạng thái của nó.

Ví dụ:

<a href="https://google.com" id="myLink">Click me</a> <script> document.getElementById("myLink").addEventListener("click", function (event) { event.preventDefault(); // Ngăn link chuyển hướng console.log("Link clicked but not redirected"); }); </script>

Kết quả:

  • Khi click vào link, nó không mở trang Googleevent.preventDefault() đã chặn hành động mặc định.

5. Kết luận

Thuật ngữĐịnh nghĩa
Event BubblingSự kiện lan truyền từ phần tử được nhắm đến lên cha của nó.
Event DelegationGắn sự kiện vào phần tử cha để xử lý sự kiện của phần tử con.
Event PropagationCách sự kiện lan truyền trong DOM (Capturing → Target → Bubbling).
Event PreventingNgăn chặn hành vi mặc định của trình duyệt bằng event.preventDefault().

Understanding Event Bubbling, Delegation, Propagation, and Preventing in JavaScript

A detailed explanation of how events propagate in the DOM, how to delegate events, and prevent default behaviors.

Understanding Event Bubbling, Delegation, Propagation, and Preventing in JavaScript

In JavaScript, event handling is an important aspect of user interaction. When an event occurs, it not only affects the target element but can also propagate through the DOM in various ways.

Today, we will explore four key concepts:

  1. Event Bubbling
  2. Event Delegation
  3. Event Propagation
  4. Event Preventing

1. Event Bubbling

What is Event Bubbling?
Event Bubbling is the process where an event starts from the target element and then propagates up the DOM tree to its parent elements.

Example:
When you click a <button> inside a <div>, the click event is not only triggered on the <button> but also propagates up to the <div> and other parent elements.

<div id="parent"> <button id="child">Click me</button> </div> <script> document.getElementById("child").addEventListener("click", function () { console.log("Button clicked!"); }); document.getElementById("parent").addEventListener("click", function () { console.log("Div clicked!"); }); </script>

Result:

  • When you click the button, the console will log:
Button clicked!
Div clicked!
  • This happens because the event starts from the button and bubbles up to the div.

2. Event Delegation

What is Event Delegation?
Event Delegation is a technique where you attach the event listener to the parent element rather than to each individual child element.

Why use Event Delegation?

  • It reduces the number of event listeners, improving performance.
  • It's useful when the list of elements changes dynamically (e.g., a todo list).

Example:
Instead of attaching a click event to each button, we can attach it to the parent ul element:

<ul id="menu"> <li>Home</li> <li>About</li> <li>Contact</li> </ul> <script> document.getElementById("menu").addEventListener("click", function (event) { if (event.target.tagName === "LI") { console.log("You clicked:", event.target.innerText); } }); </script>

Benefits:

  • If you later add <li> elements, the event listener still works without needing to attach new listeners.
  • Helps keep the code clean and efficient.

3. Event Propagation

What is Event Propagation?
Event Propagation is the process by which events travel through the DOM in two main phases:

  1. Capturing Phase → The event travels from document down to the target element.
  2. Bubbling Phase → The event travels from the target element back up to document.

Example:

<div id="outer"> <button id="inner">Click Me</button> </div> <script> document.getElementById("outer").addEventListener( "click", function () { console.log("Div clicked!"); }, true // Capture the event in the capturing phase ); document.getElementById("inner").addEventListener( "click", function () { console.log("Button clicked!"); } ); </script>

Result:
If you click the button, the log order will be:

Div clicked!
Button clicked!
  • The <div> event is processed first because it's in the capturing phase (with true).
  • Without true, the <button> event would be processed first due to the default bubbling phase.

4. Event Preventing

What is Event Preventing?
Event Preventing is used to block the default behavior of the browser, for example:

  • Preventing form submission when no data is entered.
  • Blocking <a> link navigation.
  • Preventing a checkbox from changing its state.

Example:

<a href="https://google.com" id="myLink">Click me</a> <script> document.getElementById("myLink").addEventListener("click", function (event) { event.preventDefault(); // Prevent the link from redirecting console.log("Link clicked but not redirected"); }); </script>

Result:

  • When you click the link, it does not navigate to Google because event.preventDefault() blocked the default action.

5. Conclusion

TermDefinition
Event BubblingThe event propagates from the target element up to its parent elements.
Event DelegationAttach the event listener to the parent element to handle events for child elements.
Event PropagationThe process of an event traveling through the DOM (Capturing → Target → Bubbling).
Event PreventingPrevent the default browser behavior using event.preventDefault().

This should provide a clearer understanding of these important JavaScript concepts and how they can help you handle events more efficiently.

Tag

Buy Me A Coffee
    JavaScript