completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Predict who hears an eventFrom bubbles, composed, and where an event starts, say which listeners run: inside the root, on the host, and above it.
  • 02
    Know the built-in eventsTell which built-in events leave a shadow root, like click and input, and which stay inside, like change and toggle.
  • 03
    Choose 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:

One button, a click and an event of the card's ownPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, 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-press from the button, with bubbles: true, so it climbs up.
  • Lines 10 to 12 listen on the shadow root. They print the event's composed flag.
  • On the page, lines 5 to 7 listen for clicks on document. Lines 8 to 10 listen for add-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.

Two rows of cards for one click on Add Oolong. The click's path: button, ShadowRoot, tea-card, body, html, document, window. The add-press event's path has the same cards, but everything after ShadowRoot is faded and crossed out. A dashed line marks the edge of the card's shadow root.click, composed truebuttonShadowRoottea-cardbodyhtmldocumentwindowadd-press, composed falsebuttonShadowRoottea-cardbodyhtmldocumentwindowthe edge of the card's shadow root
One click on Add Oolong, two events. The click is composed, so its path goes on past the shadow root to the page. add-press isn't, so its path ends at the shadow root.
Real-life analogyWalkie-talkies and the shop loudspeaker

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
The main idea

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.

Playground: who hears add-press?
A card in a section, and five listenersPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Everyone hears it

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.

Only line 19 changes. Click Add Oolong in the result. Each listener prints where it sits when it hears the event.
  • 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 document on 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-press from 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.

Who hears add-press on the way up
Options on line 19Inside the shadow rootOn tea-card, the hostOn section, the host's parentOn 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, from the DOM StandardText
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:

  1. The path has reached a shadow root. The shadow root picks the next stop up.
  2. There's no next stop when the event isn't composed...
  3. ...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.
  4. 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:

Playground: where does the event start?
One event, three possible starting pointsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
It started inside the root, so it stops at the root

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.

Only line 12 changes. The event bubbles and isn't composed. It's dispatched once, as the page loads, so the console shows the result right away.
  • 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, with bubbles and without composed.
  • In the tea-card.js tab, 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.

Three rows of cards: the path of the same event, which bubbles and isn't composed, from three starting points. It starts on the button inside the root: button, ShadowRoot, tea-card (not reached), body (not reached), html (not reached), document (not reached). It starts on tea-card, the host: tea-card, body, html, document. It starts on the page's own span: span, slot, h3, ShadowRoot, tea-card, body, html, document. A dashed line marks the edge of the card's shadow root.starts on the button inside the rootbuttonShadowRoottea-cardbodyhtmldocumentstarts on tea-card, the hosttea-cardbodyhtmldocumentstarts on the page's own spanspansloth3ShadowRoottea-cardbodyhtmldocumentthe edge of the card's shadow root
The same event from three places. Only the one that started inside the card's shadow root stops at its edge. The one from the host never meets a shadow root, and the span's passes through the card's.

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.

Real-life analogyA notice in the shop window

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.

Built-in events inside a shadow root
Which eventWhat causes itDoes it bubble?Does it leave a shadow root?
click, pointerdown, wheelA click, a press, or a scroll wheel.Yes.Yes. It goes on up to the page.
keydown, keyupA key press.Yes.Yes. It goes on up to the page.
beforeinput, inputTyping in a text box.Yes.Yes. It goes on up to the page.
focusin, focusoutFocus moving.Yes.Yes. It goes on up to the page.
focus, blurFocus moving.No.Yes, but only as far as the host.
changeA text box losing focus after an edit.Yes.No. It stays inside the shadow root.
selectSelecting text in a text box.Yes.No. It stays inside the shadow root.
resetA form's reset button.Yes.No. It stays inside the shadow root.
toggleOpening a <details>.No.No. It stays inside the shadow root.
scrollScrolling a box.No.No. It stays inside the shadow root.
loadAn image finishing loading.No.No. It stays inside the shadow root.
slotchangeA 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.

Real-life analogyA wave anyone can see, a beep only staff hear

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:

A text box inside a shadow root, heard from the pagePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-note.js tab, line 5 puts a label and a text box in the shadow root. Lines 6 to 8 print every change the root hears.
  • On the page, lines 6 to 8 listen on the note for input. Lines 9 to 11 listen for change.

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:

Who made the event decides composedPop out in the code editor (opens in a new tab)JavaScript
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-add event with bubbles only. Line 2 prints false. The DOM Standard starts composed as false for every event you make.
  • Line 5 listens for clicks on a button. Line 6 calls click(), which has the browser fire a click. It prints true.
  • Line 7 dispatches a click made with new MouseEvent(). It prints false.

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:

A quantity part inside the card's shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-quantity.js tab, line 8 adds 1, and line 9 shows it. Line 10 dispatches quantity-change from the part itself, with bubbles and without composed.
  • 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.

Real-life analogyNot every message goes on the loudspeaker

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-change and 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 refresh reaches 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, and composed: true, and document it. The kit's tea-timer-done does 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.
Compose it, or keep it private?
  • tea-add, when the reader presses Add on a tea card
  • quantity-change, from the quantity part inside the card
  • tea-timer-done, when a brewing timer finishes
  • slide-end, when a carousel's inner track stops moving, so the carousel can update its dots
  • refresh, from a menu's own Refresh button to the menu's list
  • tea-order-sent, when an order form has sent the order
Try it yourself
0 of 6 correct

Sort each event by who needs to hear it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

The kit's card and panel, and one listener for tea-addPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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-change on 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 TeaAddEvent from the host.
  • Lines 21 to 31 are that class. Line 25 makes every tea-add bubble and be composed. Lines 27 and 29 give it two fields, tea and quantity.
  • 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.
Two windows side by side. Left, the card's root: an arrow labelled quantity-change goes from tea-quantity up to the card's listener, and stops there. Right, the page: an arrow labelled tea-add goes from tea-card, the host, up to document. A curved arrow leads from the card's listener to tea-card.card's rootpagecard's listenerquantity-changetea-quantitydocumenttea-addtea-cardon Add, the card dispatches tea-add from its host
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.
Real-life analogyA waiter passes on only what the table needs

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-change inside 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. composed starts as false for new Event() and new CustomEvent(). Pass composed: 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 composed once 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, and slotchange stay 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 Event can carry its own fields.
  • "The page hears focus, since it's composed." No. focus doesn't bubble. Listen for focusin higher up.

Practice exercises

For each one, ask where the event starts, and whether it bubbles and is composed. Then check in the result.

Exercise 1 · Warm-upAn event from the host

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA details element in a shadow root

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticePass change on from the host

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeThe cart reloads by mistake

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeRead the event, not the target

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeTwo shadow roots, no bubbling

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, find where the event starts. Then ask whether it bubbles, and whether it's composed.

              The composed events quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does new CustomEvent("tea-add", { bubbles: true }).composed give?

                Choose an answer to see the explanation.

              2. Question 2 of 8A button inside a card's shadow root dispatches an event with { composed: true } and no bubbles. Which listener on the way up hears it?

                Choose an answer to see the explanation.

              3. 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.

              4. Question 4 of 8A card that dispatches tea-add with { bubbles: true } from its host now sits inside another component's shadow root. Does document hear it?

                Choose an answer to see the explanation.

              5. 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.

              6. 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 document hear it?

                Choose an answer to see the explanation.

              7. Question 7 of 8Why not give every event composed: true?

                Choose an answer to see the explanation.

              8. Question 8 of 8focus is 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. composed is read-only, and set when the event is made.
              • bubbles and composed are separate. Composed alone reaches the host and capturing listeners, not the host's parents on the way up.
              • composed matters 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, and slotchange stay inside.
              • Events you make start with composed: false. A click from element.click() is composed; one from new 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 Event is cleaner than detail, 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:

              Coming next: Focus and shadow DOM. Track and move focus inside a component, and make the host take focus like a built-in control.

              CompleteFrontend Clear concepts. Working examples.