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


