Happylab Logo
Published on

Day25: Event Capture, Propagation, Bubbling and Once

Authors

Introduction: How to understand event capture, propagation, bubbling, and one-time events using JavaScript.

Project Page: https://iris1114.github.io/javascript30/25_Event%20Capture-Propagation-Bubbling-and-Once/

HTML

  • Contains multiple nested div elements to demonstrate event capture, propagation, and bubbling.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Understanding JavaScript's Capture</title>
  </head>
  <body class="bod">
    <div class="one">
      <div class="two">
        <div class="three"></div>
      </div>
    </div>

    <style>
      html {
        box-sizing: border-box;
      }

      *,
      *:before,
      *:after {
        box-sizing: inherit;
      }

      div {
        width: 100%;
        padding: 100px;
      }

      .one {
        background: thistle;
      }

      .two {
        background: peachpuff;
      }

      .three {
        background: lightblue;
      }
    </style>

    <script src="scripts.js"></script>
  </body>
</html>

JavaScript

  • Uses JavaScript to demonstrate event capture, propagation, bubbling, and one-time events.
const divs = document.querySelectorAll('div')

function logText(e) {
  console.log(this.classList.value)
  e.stopPropagation() // 停止事件冒泡
}

divs.forEach((div) =>
  div.addEventListener('click', logText, {
    capture: false, // 設置為 true 以啟用事件捕獲
    once: true, // 事件處理器只運行一次
  })
)

Note

  • Uses e.stopPropagation() to stop event bubbling.
  • Uses the event listener option { capture: true } to enable event capture.
  • Uses the event listener option { once: true } to make the event handler run only once.