Composed events
Learn how composed events leave shadow DOM: what composed: true does with bubbles, which built-in events cross, and when to keep your own events private.
- 01Predict who hears an eventFrom
bubbles,composed, and where an event starts, say which listeners run: inside the root, on the host, and above it. - 02Know the built-in eventsTell which built-in events leave a shadow root, like
clickandinput, and which stay inside, likechangeandtoggle. - 03Choose for your own eventsCompose the events that are part of a component's public API, keep the rest private, and pass news on from the host.
What is a composed event?
Ravi's tea card has an Add Oolong button. When it's pressed, the card's own code sends an event called add-press. Asha spots the name in Ravi's code. She listens for add-press on her page. Nothing happens. Yet her click listener, on the same page, hears every press of that button.
Lesson 5.3 showed the short answer: an event made inside a shadow root stops at its top, unless it's composed. But who decides which events are? And how should you decide for yours?
A composed event is an event that may leave the shadow root it started in. Its composed flag is true. The browser makes clicks, key presses, and typing composed. An event you make with new Event() or new CustomEvent() isn't, unless you pass composed: true.
Here are Ravi's card and Asha's page:
<tea-card></tea-card> <script src="tea-card.js"></script><script> document.addEventListener("click", (event) => { console.log("On the page: click, composed", event.composed); }); document.addEventListener("add-press", () => { console.log("On the page: add-press"); });</script>- In the
tea-card.jstab, line 5 puts the button in the card's shadow root. A shadow root is the card's private tree, from lesson 6.1. - Lines 7 to 9 run when the button is clicked. Line 8 dispatches
add-pressfrom the button, withbubbles: true, so it climbs up. - Lines 10 to 12 listen on the shadow root. They print the event's
composedflag. - On the page, lines 5 to 7 listen for clicks on
document. Lines 8 to 10 listen foradd-press.
Click Add Oolong. The console prints Inside the card: add-press, composed false, then On the page: click, composed true. Line 9 on the page never prints. Both events started at the same button, and both bubble. Only the click got out.
add-press isn't, so its path ends at the shadow root.Leaf and Kettle's staff talk on walkie-talkies: "Oolong is low", "Table four wants water". Only the staff hear it. When something is for everyone, like "We close in ten minutes", they use the shop loudspeaker. Every customer hears that.
- In real life: The staff's walkie-talkies
- In JavaScript: An event that isn't composed
- In real life: The staff who hear them
- In JavaScript: Listeners inside the shadow root
- In real life: The shop loudspeaker
- In JavaScript: An event with
composed: true - In real life: The customers in the shop
- In JavaScript: Listeners outside: the host and the page
composed decides whether an event may leave the shadow root it started in. The browser's clicks, key presses, and typing are composed. Events you make aren't, until you pass composed: true. Leave it off, and the event stays private to the component.
The composed property is read-only. You choose it once, in the options you pass when you make the event. The DOM Standard calls it the composed flag.
Why it matters: a component's inside can talk freely, and its private events never reach the page by accident. When the page needs to know something, the component picks which events leave.
How do bubbles and composed work together?
An event has two separate switches. bubbles says whether it climbs up through its parents after its target. composed says whether it may leave its shadow root. Lesson 5.3 tried the four mixes once. Here is a fuller test: a card inside a <section>, and a listener at every level.
<section> <tea-card></tea-card></section> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); function listen(node, name, capture = false) { node.addEventListener("add-press", () => console.log(name), { capture }); } listen(document, "document, on the way down", true); listen(card.shadowRoot, "shadow root"); listen(card, "tea-card"); listen(document.querySelector("section"), "section"); listen(document, "document"); const button = card.shadowRoot.querySelector("button"); button.addEventListener("click", () => { const options = { bubbles: true, composed: true }; button.dispatchEvent(new Event("add-press", options)); });</script>All five listeners print: the capturing one on the way down, then the shadow root, the host, the section, and the document on the way up.
- Lines 8 to 10 are a small helper.
listen()adds a listener that prints a name. Its third parameter,capture, makes the listener run on the way down instead. - Line 11 listens on
documenton the way down. Lines 12 to 15 listen on the way up: on the shadow root, the card, the section, and the document. - Lines 18 to 21 dispatch
add-pressfrom the button when you click it. Line 19 holds the options. Your choice changes it.
Try each choice, and click Add Oolong each time. Here is what the four listeners on the way up print. Read each row across: the options, then whether each listener hears the event.
| Options on line 19 | Inside the shadow root | On tea-card, the host | On section, the host's parent | On document |
|---|---|---|---|---|
{} | Doesn't hear it. | Doesn't hear it. | Doesn't hear it. | Doesn't hear it. |
{ bubbles: true } | Hears it. | Doesn't hear it. | Doesn't hear it. | Doesn't hear it. |
{ composed: true } | Doesn't hear it. | Hears it. | Doesn't hear it. | Doesn't hear it. |
{ bubbles: true, composed: true } | Hears it. | Hears it. | Hears it. | Hears it. |
Look at the { composed: true } row. The event left the shadow root, but on the way up only the host heard it. To the host, the event happened right there, at its target, as lesson 9.1 showed. The section and the document never heard it. So composed doesn't make an event bubble. It only lets it out of the root. Lit's docs put it the same way: a composed event that doesn't bubble reaches the element that dispatched it and the host.
Now the listener on the way down. It printed for both composed choices, bubbling or not. On the way down, an event visits every node on its path, and a composed event's path goes all the way to the window. Bubbling and capturing covers the two trips. So a capturing listener higher up can hear a composed event that doesn't bubble. Westbrook Johnson walks through the same case.
Why it matters: for an event the page should hear, set both. With composed alone, only the host and capturing listeners hear it. Focus works that way, as the section on built-in events shows.
When does composed make a difference?
Lesson 5.3 said something surprising. A component that dispatches from its host, with this.dispatchEvent(), doesn't need composed while it sits on the page. Why not? The DOM Standard answers it in one sentence.
Before any listener runs, the browser works out the event's path. It starts at the target and asks each node for the next one up. The standard calls this step get the parent. Here is the shadow root's version, word for word. "Returns null" means there's no next stop. "Unset" means false.
A shadow root's get the parent algorithm, given an event, returns
null if event's composed flag is unset
and shadow root is the root of event's path's first event path item's invocation target;
otherwise shadow root's host.In plain words, line by line:
- The path has reached a shadow root. The shadow root picks the next stop up.
- There's no next stop when the event isn't composed...
- ...and the event started in this very shadow root. The path's first item is the node the event started at, and its root is the top of that node's tree.
- In every other case, the next stop is the host.
So composed matters in one place only: the top of the shadow root where the event started. Try the same event from three places. It bubbles, and it isn't composed:
<tea-card> <span slot="name">Oolong</span></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); card.shadowRoot.addEventListener("tea-ping", () => console.log("shadow root")); card.addEventListener("tea-ping", () => console.log("tea-card")); document.addEventListener("tea-ping", () => console.log("document")); const start = card.shadowRoot.querySelector("button"); start.dispatchEvent(new Event("tea-ping", { bubbles: true }));</script>The button lives in the card's shadow root. The event climbs to that root and stops there. It isn't composed, and this is the root it started in.
- Lines 8 to 10 listen on the card's shadow root, on the card, and on the document.
- Line 12 picks where the event starts. Line 13 dispatches
tea-ping, withbubblesand withoutcomposed. - In the
tea-card.jstab, line 5 gives the card a name slot and a button.
From the button inside, the console prints only shadow root. From the host, it prints tea-card and document. From the span, it prints all three: shadow root, tea-card, and document.
Look at the host first. Its event never passes a shadow root. The card's own shadow root sits below the card, not above it. That's why this.dispatchEvent() reaches the page without composed, as long as the card sits in the page's own tree.
Now the span. It's the page's own node, shown in the card's name slot. On the way up, a slotted node's next stop is its slot, so the event goes into the card's shadow root. But it didn't start there, so the root lets it go on. Lesson 8.4 saw the same thing: a slotchange from the panel's slot climbed through the card's slot.
A note pinned up in Leaf and Kettle's back office stays there. Only staff read it, unless someone carries it out. A poster in the front window is different. It's already facing the street, so everyone walking past can read it.
- In real life: A note pinned up in the back office
- In JavaScript: An event that starts inside the shadow root
- In real life: Carrying it out to the street
- In JavaScript:
composed: true - In real life: A poster in the front window
- In JavaScript: An event dispatched on the host
- In real life: People walking past
- In JavaScript: The page's listeners
Chrome's code follows the same rule. GetShadowRootParent(), in Chromium's event_path.cc, gives back the host when the event is composed, or when the event's target isn't in that shadow root. Otherwise it gives back nothing.
Why it matters: ask where your event starts. From inside your shadow root, it needs composed: true to get out. From your host, it doesn't, until someone puts your element inside their own shadow root. Nested roots come next, after the built-in events.
Which built-in events are composed?
The browser fires most events itself. MDN gives the rule in one line: every UI event the browser dispatches is composed. UI events come straight from the person using the page: clicks, key presses, typing, and focus. Most other events aren't composed.
Here are common ones, each made to happen in Chrome inside a shadow root. Read each row across: the event, what causes it, whether it bubbles, and whether it leaves a shadow root.
| Which event | What causes it | Does it bubble? | Does it leave a shadow root? |
|---|---|---|---|
click, pointerdown, wheel | A click, a press, or a scroll wheel. | Yes. | Yes. It goes on up to the page. |
keydown, keyup | A key press. | Yes. | Yes. It goes on up to the page. |
beforeinput, input | Typing in a text box. | Yes. | Yes. It goes on up to the page. |
focusin, focusout | Focus moving. | Yes. | Yes. It goes on up to the page. |
focus, blur | Focus moving. | No. | Yes, but only as far as the host. |
change | A text box losing focus after an edit. | Yes. | No. It stays inside the shadow root. |
select | Selecting text in a text box. | Yes. | No. It stays inside the shadow root. |
reset | A form's reset button. | Yes. | No. It stays inside the shadow root. |
toggle | Opening a <details>. | No. | No. It stays inside the shadow root. |
scroll | Scrolling a box. | No. | No. It stays inside the shadow root. |
load | An image finishing loading. | No. | No. It stays inside the shadow root. |
slotchange | A slot's content changing. | Yes. | No. It stays inside the shadow root. |
The standards set these flags. The HTML Standard fires input "with the bubbles and composed attributes initialized to true", and change with only bubbles. UI Events lists focus as composed, but not bubbling.
When a customer waves or calls out, everyone in the shop notices. When the till beeps as its drawer closes, only the staff behind the counter hear it. That beep is news about the till, for the people who run it.
- In real life: A customer waving or calling out
- In JavaScript: A click, a key press, typing
- In real life: Everyone in the shop notices
- In JavaScript: UI events are composed
- In real life: The till's beep when a drawer closes
- In JavaScript:
change,toggle,slotchange - In real life: Only staff behind the counter hear it
- In JavaScript: They stay inside the shadow root
The change row surprises people most. Here is a text box in a shadow root:
<tea-note></tea-note> <script src="tea-note.js"></script><script> const note = document.querySelector("tea-note"); note.addEventListener("input", (event) => { console.log("Page: input, composed", event.composed); }); note.addEventListener("change", () => { console.log("Page: change"); });</script>- In the
tea-note.jstab, line 5 puts a label and a text box in the shadow root. Lines 6 to 8 print everychangethe root hears. - On the page, lines 6 to 8 listen on the note for
input. Lines 9 to 11 listen forchange.
Click in the box, type one letter, then press Tab. The console prints Page: input, composed true, then Inside: change, composed false. Line 10 never prints. The page hears every keystroke, but never hears that the edit is done. So a component that wraps a text box passes change on itself, from its host. Exercise 3 does that.
Focus follows the focus row: composed, but not bubbling. A listener on the host hears focus when the inner text box gets focus. A listener on document doesn't. Higher up, listen for focusin and focusout, which bubble. When focus moves between two elements inside the same shadow root, the host and the page hear none of these events. Focus and shadow DOM, the next lesson, explains why.
Clicks you make yourself
The flag belongs to the event, not to its name. A click the browser fires is composed. A click you make isn't, unless you say so:
const made = new CustomEvent("tea-add", { bubbles: true });
console.log(made.composed);
const button = document.createElement("button");
button.addEventListener("click", (event) => console.log(event.composed));
button.click();
button.dispatchEvent(new MouseEvent("click"));- Line 1 makes a
tea-addevent withbubblesonly. Line 2 printsfalse. The DOM Standard startscomposedasfalsefor every event you make. - Line 5 listens for clicks on a button. Line 6 calls
click(), which has the browser fire a click. It printstrue. - Line 7 dispatches a click made with
new MouseEvent(). It printsfalse.
Why it matters: a test that clicks with new MouseEvent("click") won't leave a shadow root, but a real click does. Use element.click(), or pass bubbles: true and composed: true.
How do events cross nested shadow roots?
Components hold other components. Ravi gives his card a quantity part, <tea-quantity>, inside the card's shadow root. It has a + button and a number. When the number changes, it tells the card:
<tea-card></tea-card> <script src="tea-quantity.js"></script><script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.innerHTML = "Oolong <tea-quantity></tea-quantity>"; this.shadowRoot.addEventListener("quantity-change", (event) => { console.log("The card heard it:", event.target.value); }); } } customElements.define("tea-card", TeaCard); document.addEventListener("quantity-change", (event) => { console.log("The page heard it from", event.target.localName); });</script>- In the
tea-quantity.jstab, line 8 adds 1, and line 9 shows it. Line 10 dispatchesquantity-changefrom the part itself, withbubblesand withoutcomposed. - On the page, line 9 puts the part in the card's shadow root. Lines 10 to 12 listen on that root, and print the number.
- Lines 17 to 19 listen on the page.
Click +. The console prints The card heard it: 2. The page prints nothing. The event started on tea-quantity, inside the card's shadow root. So it climbed to that root and stopped. The part talks to the card, and to nobody else.
Now press Edit & run, open the tea-quantity.js tab, and change line 10's options to { bubbles: true, composed: true }. Then click + again. Two lines print: The card heard it: 2, then The page heard it from tea-card. The event crossed the card's root, and would cross every root above it. At each one, the browser retargets it, so the page sees the card, as in lesson 9.1.
That works, but look at what the page got. An event called quantity-change, which the card never documented, from a part the page can't see. If Ravi renames the part, or swaps it for a drop-down list, the page's code breaks.
One more detail. A composed event that doesn't bubble is heard by every host on its way out, each at its target. Exercise 6 has two shadow roots, so two hosts hear it.
When should you not compose an event?
Lesson 5.3 gave public events composed: true. Why not set it on every event? Westbrook Johnson weighs it in "composed: true considered harmful?". He calls composed: false the private fields of DOM events. Inside its shadow root, a component can fire any events it likes, and nobody outside hears them.
Imagine Leaf and Kettle's staff using the loudspeaker for everything: "Milk is low", "Ravi, check the kettle". Customers would hear a stream of noise. A customer who is also called Ravi would look up, thinking it's for him. So the loudspeaker is only for what customers need.
- In real life: Staff chatter on the loudspeaker
- In JavaScript: Internal events with
composed: true - In real life: Customers hearing all of it
- In JavaScript: The page hearing every internal event
- In real life: A customer called Ravi who looks up
- In JavaScript: A page listener with the same event name
- In real life: "Table four, your tea is ready"
- In JavaScript: One documented public event, like
tea-add
Composing an internal event has three costs:
- It leaks your inside. The page can listen for
quantity-changeand start to depend on it. Then you can't rename or remove it without breaking someone's page. - Its name can clash. Westbrook points out that a composed event can be heard from far away, so its name matters more. A common name like
refreshreaches every listener for that name on the page. Exercise 4 shows a page reloading its cart by mistake. - It adds noise. If every nested component composes its events, all of them reach the top of the page.
So choose for each event. Ask who needs to hear it:
- The page, wherever your element sits. The event is part of your public API. Give it your prefix,
bubbles: true, andcomposed: true, and document it. The kit'stea-timer-donedoes this. - Only your own shadow root. Dispatch it inside, without
composed. - Only the tree your element sits in. Dispatch it on your host, without
composed. The event then stops at the top of that tree. javascript.info gives this tip for an event meant only for the component just outside yours.
tea-add, when the reader presses Add on a tea cardquantity-change, from the quantity part inside the cardtea-timer-done, when a brewing timer finishesslide-end, when a carousel's inner track stops moving, so the carousel can update its dotsrefresh, from a menu's own Refresh button to the menu's listtea-order-sent, when an order form has sent the order
Sort each event by who needs to hear it.
And when an inner event matters to the page? Don't compose it. Catch it, and announce your own event from the host. Westbrook describes it this way: handle the private events inside, then dispatch a new, clearly documented event when it's ready. The next section builds that into the kit.
Passing an event on from the tea card
Time to put this in Ravi's kit. The card gets a quantity part and an Add button. The page wants one thing: what was added, and how many. Here is the kit's card on a page, next to the kit's panel from lesson 8.3, which holds a card in its own shadow root:
<tea-card name="Green tea" price="4"></tea-card><tea-panel> <span slot="heading">Oolong</span></tea-panel> <script type="module"> import "./tea-kit/index.js"; import { TeaAddEvent } from "./tea-kit/tea-card.js"; document.addEventListener(TeaAddEvent.type, (event) => { console.log(`Added ${event.quantity} ${event.tea}, heard from ${event.target.localName}`); }); document.addEventListener("quantity-change", () => { console.log("The page heard quantity-change"); });</script>- Line 1 is a card. Lines 2 to 4 are the panel, with Oolong slotted in as its heading.
- Line 8 imports
TeaAddEvent, the card's event class. Line 10 listens for its name,TeaAddEvent.type. - Line 11 prints the quantity and the tea from the event, and the target this listener reads.
- Lines 13 to 15 listen for
quantity-change, the part's private event.
Press + once on the Green tea card, then its Add 2 button. The console prints Added 2 Green tea, heard from tea-card. Now press Add 1 in the panel. It prints Added 1 Oolong, heard from tea-panel. Line 14 never prints.
Open the tea-kit/tea-quantity.js tab. Line 32 dispatches quantity-change with bubbles and without composed, so it stays in the card's shadow root. Then open tea-kit/tea-card.js:
- Line 1 imports the part. Line 17 puts it in the card, next to the Add button.
- Lines 56 to 59 listen for
quantity-changeon the card's shadow root. They keep the number, and write it on the button. - Lines 60 to 62 run when Add is pressed. They dispatch a
TeaAddEventfrom the host. - Lines 21 to 31 are that class. Line 25 makes every
tea-addbubble and be composed. Lines 27 and 29 give it two fields,teaandquantity. - Lines 65 to 68 read the tea's name from the name slot's flattened nodes, as in lesson 8.3, so a slotted name works too.
quantity-change isn't composed, so it stays in the card's root, where the card keeps the number. When the reader presses Add, the card dispatches tea-add from its host, and the page hears that.In Leaf and Kettle's kitchen, the cooks talk all the time: the water's hot, two cups not one, the green tea tin is open. The waiter hears it all. At the table, she says one sentence: "Two cups of green tea, coming up."
- In real life: The kitchen's talk
- In JavaScript:
quantity-changeinside the card - In real life: The waiter who hears it
- In JavaScript: The card's listener on its shadow root
- In real life: "Two cups of green tea, coming up"
- In JavaScript:
tea-add, dispatched from the host - In real life: The table
- In JavaScript: The page's listener
Why is tea-add composed, when the card dispatches it from its host? Because the host isn't always on the page. In the panel, the card lives in the panel's shadow root. Without composed: true, its tea-add would stop at the panel's root, and the page would never hear the Oolong. Composed, it gets out, retargeted to tea-panel.
The card dispatches tea-add only when the reader presses Add, never when the page sets an attribute. web.dev's Custom Element Best Practices gives that rule: dispatch for activity inside the component, not for changes the page made.
Where the event's data goes
Look at the target in the second line: tea-panel. A page that read the tea's name from event.target would get the panel, not the card. That's why tea-add carries its data on the event itself. Exercise 5 shows the bug.
Many people reach for new CustomEvent() and its detail for this. That's a habit, not a rule. Justin Fagnani's "Stop Using CustomEvent" says CustomEvent was added before JavaScript could easily extend built-in classes. A class that extends Event, like TeaAddEvent, puts the fields right on the event, and sets its options in one place. Lesson 5.3 built one for the timer.
Fagnani also notes that many built-in events carry no data at all, like input and change. The listener reads event.target instead. That works when the target is the element you mean. For a composed event, it may be an outer host.
Common mix-ups
- "Events I make cross shadow roots, like clicks do." No.
composedstarts asfalsefornew Event()andnew CustomEvent(). Passcomposed: true. - "composed: true makes an event bubble." No. Without
bubbles, it reaches the host and stops. Only capturing listeners above the host hear it. - "An event from this.dispatchEvent() needs composed to reach the page." No. It starts on the host, in the page's tree. It needs
composedonce your element sits in another shadow root. - "A shadow root stops every event that isn't composed." No. It stops only events that started inside it. An event from a slotted node passes through.
- "Every built-in event is composed." No. UI events are.
change,select,reset,toggle,scroll,load, andslotchangestay inside. - "Always set composed: true." No. Internal events then leak to the page, and common names clash with its listeners. Compose your public events only.
- "Event data has to go in detail." No. That's a habit. A class that extends
Eventcan carry its own fields. - "The page hears focus, since it's composed." No.
focusdoesn't bubble. Listen forfocusinhigher up.
Practice exercises
For each one, ask where the event starts, and whether it bubbles and is composed. Then check in the result.
Click Add Oolong. What does the console print?
<main> <tea-card></tea-card></main> <script> class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<button>Add Oolong</button>"; this.shadowRoot.querySelector("button").addEventListener("click", () => { this.dispatchEvent(new Event("tea-add", { bubbles: true })); }); } } customElements.define("tea-card", TeaCard); document.addEventListener("tea-add", (event) => { console.log(`Heard tea-add from ${event.target.localName}, composed ${event.composed}`); });</script>Heard tea-add from tea-card, composed false. The event starts on the host, so it bubbles up through main to document without composed. Its flag stays false.
Click How long to steep? The page listens for click and toggle, on the way down. Which event does it hear?
<tea-faq></tea-faq> <script> class TeaFaq extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<details><summary>How long to steep?</summary>Three minutes.</details>"; } } customElements.define("tea-faq", TeaFaq); for (const type of ["click", "toggle"]) { document.addEventListener(type, () => console.log("The page heard", type), { capture: true }); }</script>Only click. A click is composed, so its path goes up to document. toggle isn't composed, so its path ends at the shadow root, and even a capturing listener on document never hears it.
Type Less sugar and press Tab. Nothing prints. Make the note tell the page. What does the fixed page print?
<tea-note></tea-note> <script> class TeaNote extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<label>Note <input></label>"; // Your code: tell the page when the note changes. } get value() { return this.shadowRoot.querySelector("input").value; } } customElements.define("tea-note", TeaNote); const note = document.querySelector("tea-note"); note.addEventListener("change", () => console.log("Saved:", note.value));</script><tea-note></tea-note> <script> class TeaNote extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<label>Note <input></label>"; const input = this.shadowRoot.querySelector("input"); input.addEventListener("change", () => this.dispatchEvent(new Event("change", { bubbles: true }))); } get value() { return this.shadowRoot.querySelector("input").value; } } customElements.define("tea-note", TeaNote); const note = document.querySelector("tea-note"); note.addEventListener("change", () => console.log("Saved:", note.value));</script>Saved: Less sugar. The text box's own change isn't composed, so the page never heard it. Line 9 listens for it inside, and dispatches a new change from the host. Like the built-in one, it bubbles and isn't composed, and it means the same thing: the edit is done.
Click Refresh list. The page reloads the whole cart, which it shouldn't. Fix the menu, not the page. What does one click print after the fix?
<tea-menu></tea-menu> <script> class TeaMenu extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<button>Refresh list</button>"; const button = this.shadowRoot.querySelector("button"); button.addEventListener("click", () => { const options = { bubbles: true, composed: true }; button.dispatchEvent(new Event("refresh", options)); }); this.shadowRoot.addEventListener("refresh", () => console.log("Menu: list refreshed")); } } customElements.define("tea-menu", TeaMenu); document.addEventListener("refresh", () => console.log("Page: reloading the whole cart"));</script><tea-menu></tea-menu> <script> class TeaMenu extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<button>Refresh list</button>"; const button = this.shadowRoot.querySelector("button"); button.addEventListener("click", () => { const options = { bubbles: true }; button.dispatchEvent(new Event("refresh", options)); }); this.shadowRoot.addEventListener("refresh", () => console.log("Menu: list refreshed")); } } customElements.define("tea-menu", TeaMenu); document.addEventListener("refresh", () => console.log("Page: reloading the whole cart"));</script>Menu: list refreshed. The menu's refresh was composed, so it reached the page's own refresh listener too. Without composed, it stays in the menu's shadow root. Its name can't clash with the page's any more.
Press Add 1 in the panel. The page prints Added null. Fix line 9. What does the fixed page print?
<tea-panel> <span slot="heading">Oolong</span></tea-panel> <script type="module"> import "./tea-kit/index.js"; document.addEventListener("tea-add", (event) => { console.log("Added", event.target.getAttribute("name")); });</script><tea-panel> <span slot="heading">Oolong</span></tea-panel> <script type="module"> import "./tea-kit/index.js"; document.addEventListener("tea-add", (event) => { console.log("Added", event.tea); });</script>Added Oolong. Outside the panel's shadow root, the target is tea-panel, so getAttribute("name") gave null. The event's own tea field holds the name the card shows.
The + button sits in tea-quantity, which sits in tea-card. Five nodes listen. Click +. How many lines print?
<tea-card></tea-card> <script> class TeaQuantity extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<button>+</button>"; const button = this.shadowRoot.querySelector("button"); button.addEventListener("click", () => { button.dispatchEvent(new Event("tea-ping", { composed: true })); }); } } class TeaCard extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<tea-quantity></tea-quantity>"; } } customElements.define("tea-quantity", TeaQuantity); customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); const quantity = card.shadowRoot.querySelector("tea-quantity"); for (const node of [quantity.shadowRoot, quantity, card.shadowRoot, card, document]) { node.addEventListener("tea-ping", () => console.log(node.nodeName)); }</script>Two: TEA-QUANTITY and TEA-CARD. Each host is a target on the path, so it hears the event. The two shadow roots and document wait for bubbling, which never comes.
Check your understanding
For each question, find where the event starts. Then ask whether it bubbles, and whether it's composed.
Question 1 of 8What does
new CustomEvent("tea-add", { bubbles: true }).composedgive?Choose an answer to see the explanation.
Question 2 of 8A button inside a card's shadow root dispatches an event with
{ composed: true }and nobubbles. Which listener on the way up hears it?Choose an answer to see the explanation.
Question 3 of 8What does the start page print when line 12 is
const start = card;?Read the code, then predictHTML<tea-card> <span slot="name">Oolong</span> </tea-card> <script src="tea-card.js"></script> <script> const card = document.querySelector("tea-card"); card.shadowRoot.addEventListener("tea-ping", () => console.log("shadow root")); card.addEventListener("tea-ping", () => console.log("tea-card")); document.addEventListener("tea-ping", () => console.log("document")); const start = card; start.dispatchEvent(new Event("tea-ping", { bubbles: true })); </script>Choose an answer to see the explanation.
Question 4 of 8A card that dispatches
tea-addwith{ bubbles: true }from its host now sits inside another component's shadow root. Doesdocumenthear it?Choose an answer to see the explanation.
Question 5 of 8A text box sits inside a shadow root. Which of its events reaches a listener on the page?
Choose an answer to see the explanation.
Question 6 of 8The page's own span sits in a card's slot. It dispatches an event that bubbles and isn't composed. Does
documenthear it?Choose an answer to see the explanation.
Question 7 of 8Why not give every event
composed: true?Choose an answer to see the explanation.
Question 8 of 8
focusis composed but doesn't bubble. How can the page hear focus moving inside a component?Choose an answer to see the explanation.
Key takeaways
- A composed event may leave the shadow root it started in.
composedis read-only, and set when the event is made. bubblesandcomposedare separate. Composed alone reaches the host and capturing listeners, not the host's parents on the way up.composedmatters only at the top of the shadow root where the event started. An event from the host, or from a slotted node, doesn't need it to reach the page.- UI events like
click,input, keys, and focus are composed.change,toggle,load, andslotchangestay inside. - Events you make start with
composed: false. A click fromelement.click()is composed; one fromnew MouseEvent()isn't. - A composed event crosses every shadow root on its way out, and is retargeted at each one.
- Compose your public events. Keep internal ones private, and pass on what matters with your own event from the host.
- Carry the data on the event. A class that extends
Eventis cleaner thandetail, and the target may be an outer host.
Remember the one-liner.composed lets an event out of the shadow root it started in: use it for the events the page needs, and nothing else.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- Event: composed property, MDN.
- DOM Standard: The composed flag, WHATWG.
- DOM Standard: EventInit's composed, WHATWG.
- DOM Standard: Dispatching events, WHATWG.
- DOM Standard: Interface ShadowRoot, its get the parent, WHATWG.
- event_path.cc, GetShadowRootParent(), at Chromium 158.0.8127.18, Chromium.
- HTML Standard: Common event behaviors of input, WHATWG.
- HTML Standard: Resetting a form, WHATWG.
- HTML Standard: The details element, WHATWG.
- UI Events: Focus events, W3C.
- CSSOM View: Scrolling events, W3C.
- HTMLSlotElement: slotchange event, MDN.
- FocusEvent, MDN.
- Events: Understanding composed event dispatching, Lit.
- composed: true considered harmful?, Westbrook Johnson, open-wc.
- Shadow DOM and events, Ilya Kantor, javascript.info.
- Stop Using CustomEvent, Justin Fagnani.
- Custom Element Best Practices: Events, web.dev.
Coming next: Focus and shadow DOM. Track and move focus inside a component, and make the host take focus like a built-in control.