In this article you will see

  • What problem does the DOM event model solve
  • What is capture and what is bubbling
  • Can capture and bubbling be cancelled

What is the DOM event model

  • Let’s start with this code:
<div class='grandpa'>
    <div class='dad'>
        <div class='son'>content</div>
    </div>
</div>
Copy the code

FnGrandpa /fnDad/fnSon; fnGrandpa/fnDad/fnSon

  1. When users click on content, they clickgrandpaordadorson?
  2. The user clicks “Content” and calls firstfnGrandpa/fnDad/fnSonWhich function in?

The answer is ambiguous: yes, both.

  • The peacemakers, the W3C, set the rules

To address these two issues, the W3C published a standard document in 2002 that provides the following:

  1. Browsers should support both call sequences
  2. See if there are functions listening in the order from outside to inside (grandpa > Dad > son), and then see if there are events listening in the order from inside to outside (son > Dad > Grandpa)
  3. If there are listener functions, call them and provide event information. If not, skip them

This is where DOM events come from

What is capture and what is bubbling?

See if there are functions listening in the order from outside to inside (grandpa > Dad > son), and then see if there are events listening in the order from inside to outside (son > Dad > Grandpa)

In this rule, looking for listeners from the outside in is called event capture, and looking for listeners from the inside out is called event bubble. By default, browsers catch listeners first and then bubble

  • The complete DOM event model is divided into three phases:
    • Capture Phase
    • Target Phase
    • Bubbling Phase

The target stage refers to the stage where the real target node is processing events, such as the user clicking “content” in the code above.

  • We can choose whether to put the listener in the capture or bubble phase
    • Event binding API
    // IE5
    dad.attachEvent('onclick',fn) / / the bubbling
    / / netscape
    dad.addEventListner('click',fn) / / capture
    / / the W3C USES
    dad.addEventListener('click', fn, bool)
    Copy the code
    • whenboolNo parameter is passed orfalsy.fnPut it in the bubble stage
    • whenboolIs true,fnPut in the capture phase

Can capture and bubbling be cancelled

  • Capture cannot be cancelled, but bubbling can
    • You can usee.stopPropagation()Interrupt the bubbling
  • You cannot block the default action
    • For example, scroll event, Scroll Event has two properties
      • BubblesIndicates whether the event bubbles
      • CancelableRefers to whether the developer can block the default event

  • All bubbles can be cancelled
  • Cancelale is not associated with bubbling