liveBook · Manning

Event bubbling

As explained in Web Components in Action

Event bubbling is DOM event propagation in which an event moves from its originating element upward through ancestor elements.

Event bubbling carries an event from its originating element through parent elements toward the document. Native events such as click bubble by default; CustomEvent instances require explicit configuration. section 14.2

Use bubbling to let an ancestor listen for events dispatched by a descendant:

  • Create a CustomEvent with detail data such as a message and number. section 14.2
  • Set bubbles: true when the custom event must pass through ancestor elements. section 14.2
  • Dispatch the event on the originating element and listen higher in the DOM, such as on document. section 14.2
  • Remember that an event without bubbling stops at its target unless the listener is attached directly there. section 14.2
Listing 14.4. Custom Event bubbling
<html>
<head>
   <title>Custom Event Bubbling</title>
   <script>
       document.addEventListener('myevent', function(e) {
           console.log('The message', e.detail.message, 'with number',
                        e.detail.number);
       });

       const event = new CustomEvent('myevent', {
           bubbles: true,                           #1
           detail: {
               message: 'hi',
               number: 5
           }
       });

       setTimeout( function() {
           document.getElementById('target')        #2
                       .dispatchEvent(event);
       }, 2000);
   </script>
</head>
<body>
   <div id="target"></div>                          #3
</body>
</html>

Inspect a complete CustomEvent example that dispatches from a target element, carries detail data, and reaches a document listener through bubbles: true. section 14.2

How Web Components in Action covers it

How deep it goes
Explains propagation through DOM layers and demonstrates CustomEvent configuration, stopping short of broader event-dispatch internals.
Examples
Demonstrates click listeners, a myevent CustomEvent, detail data, target dispatch, and document-level listening.
What it assumes
Assumes familiarity with elements and listeners while distinguishing native-event defaults from CustomEvent behavior.
What you can do after
Apply it via CustomEvent by dispatching detail data with bubbles: true and handling it from an ancestor listener.
How it connects
Connects DOM events, CustomEvent, Shadow DOM, Web Components, and event-driven application data flow.

Also explained in

Compare how 3 books explain event bubbling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.