<div class='grandfather'>
    <div class='daddy'>
        <div class='son'>The text</div>
    </div>
</div>
Copy the code

Suppose you have added event listeners fnYe/fnBa/fnEr to each of the three divs

What is capture

Looking from the outside in listener function, called event capture, that is: grandpa => Dad => son

When the user clicks a button, the browser traverses the window from top to bottom, triggering event handlers one by one.

What is bubbling

Look for the listener function from inside out, called event bubbling, that is: son => Dad => grandpa

The browser traverses the window from the bottom to the top of the button clicked by the user, triggering event handlers one by one.

Capture or bubble first problem

  • The event bubbling

Microsoft has come up with a stream of events called Event Bubbling. Event bubbling can be likened to dropping a stone into water and bubbles will continue to rise from the bottom to the surface. That is, events will start at the innermost element and propagate up to the Document object.

Take IE5 as an example, the event capture is performed first:

baba.attachEvent('onclick',fn) / / bubbling first
Copy the code
  • Event capture

Netscape proposes another stream of events called Event capturing. In contrast to event bubbling, events occur from the outermost layer up to the most concrete element.

baba.addEventListener('click',fn) / / to capture
Copy the code
  • W3C rules:

Netscape advocates capture, Microsoft advocates bubble.

In a compromise, the W3C settled on a common standard — capture now, bubble later. The third argument to addEventListener is for bubbling and capturing:

element.addEventListener('click'.function.bool)
Copy the code

The first parameter is the event to bind

The second argument is the function to execute after the event is fired

When the third parameter is empty or falsy, it means that the event handler is called during the event bubbling phase. If the argument is true, the handler is called during the event capture phase.

  • There is a special case

Cancel the bubbling

Capture cannot be cancelled. Bubbles can be interrupted by E.topPropagation ()

This article references excerpts:

  1. Event bubbling and capture in JS
  2. Describe the DOM event model or DOM event mechanism