Dispatching events
Dispatch web component custom events the way built-in elements do: CustomEvent or an Event subclass, bubbles, composed, cancelable, and clear names.
- 01Dispatch an event from a componentMake it with
new CustomEvent()or anEventsubclass, and choosebubblesandcomposedon purpose. - 02Let the page say noMake the event cancelable, check what
dispatchEvent()gives back, and skip the action when a listener calledpreventDefault(). - 03Name and time events like built-in onesUse a prefix and lowercase, update your state before you dispatch, and stay quiet about changes the page made itself.
How do you dispatch a custom event from a web component?
Ravi has made a new tag for the Leaf and Kettle shop: <tea-cup>, a cup with an Add button. Asha puts it on her page, under the cart. She presses Add. The cup knows. The cart still says 0.
The cup can't reach into Asha's page. It doesn't know her cart exists, and it shouldn't. So how does the cup tell the page that a tea was added?
A web component tells the page what happened by dispatching an event. It makes the event with new CustomEvent("tea-add", { detail, bubbles: true }), then calls this.dispatchEvent(event). To dispatch an event means to send it out from an element, so its listeners run. The page listens with addEventListener(), as it does for a click.
Here is the whole thing: Ravi's cup, and Asha's cart.
<p>Cart: <span>0</span> teas</p><tea-cup tea="Green tea"></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { const tea = this.getAttribute("tea"); this.innerHTML = `<button>Add ${tea}</button>`; this.addEventListener("click", () => { const event = new CustomEvent("tea-add", { detail: { tea }, bubbles: true, }); this.dispatchEvent(event); }); } } customElements.define("tea-cup", TeaCup); const count = document.querySelector("span"); document.addEventListener("tea-add", (event) => { count.textContent = Number(count.textContent) + 1; console.log("Added", event.detail.tea); });</script>- Line 2 puts a cup on the page, with a
teaattribute. - Lines 7 and 8 read the tea and draw a button inside the cup.
- Line 9 listens for clicks on the cup. A click on the button bubbles up to it.
- Lines 10 to 13 make the event. Its name is
tea-add. Itsdetailholds the tea, andbubbles: truelets it climb up the page. - Line 14 dispatches it on the cup itself, with
this.dispatchEvent(). - Lines 21 to 24 are Asha's part: one listener on
document. It adds 1 to the cart and prints the tea.
Press Add twice. The cart shows Cart: 2 teas, and the console prints Added Green tea twice. The cup and the cart never touch. The cup announces, and the page decides what an add means.
tea-add, with the tea in its detail, and dispatches it on itself. It bubbles up to document, where Asha's listener counts it. The cup never touches the cart.In Leaf and Kettle's kitchen, the kettle whistles when the water boils. It doesn't know who is in the room. It doesn't pour the tea either. Whoever hears the whistle decides what to do next.
- In real life: The kettle
- In JavaScript:
<tea-cup>, the component - In real life: The whistle
- In JavaScript: The
tea-addevent - In real life: Whoever hears it
- In JavaScript: The page's listeners
- In real life: Pouring the tea
- In JavaScript: The page's own work, like counting the cart
A component talks back by dispatching events. It makes the event, chooses how far it may travel, and calls this.dispatchEvent(). The page listens, and decides what to do. Properties go into a component. Events come out of it.
You've seen this from the other side. In lesson 2.2, Ravi listened for Web Awesome's wa-hide. Now he writes a component that dispatches its own events. The JavaScript path's Custom events lesson covers the API itself. This lesson is about using it well in a component.
How do CustomEvent and detail work?
new CustomEvent(type, options) makes an event object. The first part is its name, which the DOM calls its type. The second is an object of options. Leave the options out, and every one gets its default:
const event = new CustomEvent("tea-add");
console.log(event.type, event.detail);
console.log(event.bubbles, event.composed, event.cancelable);- Line 1 makes an event called
tea-add, with no options. - Line 2 prints
tea-add null. The type is the name you gave, anddetailisnull. - Line 3 prints
false false false. The event doesn't bubble, isn't composed, and can't be canceled.
The DOM Standard sets those three to false, and detail to null. Here are the four options. Read each row across: the option, its default, and what it does when you set it.
| Option | Default | What it does when you set it |
|---|---|---|
detail | null | Carries any data you give it, like { tea: "Green tea" }. Listeners read event.detail. |
bubbles | false | The event climbs from your element up to the page, so a listener higher up hears it. |
composed | false | The event may leave the shadow root it started in. |
cancelable | false | A listener may call preventDefault(), and dispatchEvent() then gives back false. |
detail can hold any value: a string, a number, or an object. The cup used an object, { tea }, so it can add more fields later. Only a CustomEvent has detail. A plain new Event() has none.
What dispatchEvent() gives back
Dispatching runs the listeners. Then dispatchEvent() gives back true or false:
const cup = document.createElement("tea-cup");
cup.addEventListener("tea-add", (event) => {
console.log("Heard", event.detail.tea);
});
const event = new CustomEvent("tea-add", { detail: { tea: "Mint tea" } });
const result = cup.dispatchEvent(event);
console.log("dispatchEvent gave", result);- Lines 2 to 4 listen on the cup for
tea-add. - Line 5 makes the event, with the tea in
detail. - Line 6 dispatches it. The listener runs right there, and prints
Heard Mint tea. - Line 7 prints
dispatchEvent gave true.
It gives back false only when the event is cancelable and a listener canceled it. The section on cancelable events puts that to work. Notice the order, too: the listener printed before line 7 ran. The section on when to dispatch shows why that matters. The Custom events lesson steps through both.
Events with no data
Not every event needs detail. Justin Fagnani points out that many built-in events carry no data of their own, like change and load. The listener reads what it needs from event.target, the element the event came from. An input's change event doesn't carry the new text, so a listener reads event.target.value. Your component can do the same. A playground below dispatches a plain new Event("tea-add"), and the page reads the cup's count.
Why should web component events bubble?
An event that bubbles climbs from its element up through each parent, all the way to document. Clicks do. The events you make don't, unless you say so. The JavaScript path's Bubbling & capturing lesson follows that trip. Here is the difference for one cup inside a shop:
const shop = document.createElement("main");
const cup = document.createElement("tea-cup");
shop.append(cup);
shop.addEventListener("tea-add", (event) => console.log("The shop heard", event.detail));
cup.dispatchEvent(new CustomEvent("tea-add", { detail: "the first add" }));
cup.dispatchEvent(new CustomEvent("tea-add", { detail: "the second add", bubbles: true }));- Lines 1 to 3 put a cup inside a
<main>element, the shop. - Line 4 listens on the shop, not on the cup.
- Line 6 dispatches the first add, with no options. Nothing prints.
- Line 7 dispatches the second add with
bubbles: true. It climbs to the shop, which printsThe shop heard the second add.
tea-add stays on the cup, so the shop's listener on <main> never runs. The second has bubbles: true, so it climbs to <main>, and the listener prints.Back in the overview, line 12 said bubbles: true. Take it out, and Asha's cart stays at 0, however often you press Add. Her listener sits on document, and the event never gets there.
Most component events should bubble, for three reasons:
- One listener for many components. Asha's page could have twenty cups and one listener on
document. That's event delegation. - A parent can listen once. A shelf that holds cups listens on itself, not on each cup.
- It matches the platform. Clicks,
input, andchangeall bubble. Lit's docs say to setbubblesso an event works with delegation. Every Web Awesome event from lesson 2.2 bubbles too.
What does the composed option do?
A shadow root is a component's private tree, from lesson 1.1. Stage 3 builds them properly. For now, one fact matters. An event that starts inside a shadow root stops at its top, unless it's composed. composed: true lets it cross out into the tree around it.
Does Ravi's cup need it? Not on Asha's page. The cup dispatches on itself, and the cup sits right in the page. So the event starts in the page's own tree, and bubbles is enough. That changes when the cup sits inside another component's shadow root.
Ravi builds a <tea-shelf>. Its shadow root holds a cup. Now the cup's event starts inside the shelf's private tree.
A cook works behind a door marked Staff only. If she mutters, only she hears it. If she calls out, the whole kitchen hears, but the diners don't. If she calls through the open door, the diners hear too. To them, the kitchen called. They can't see which cook it was.
- In real life: The cook
- In JavaScript:
<tea-cup>, inside the shelf's shadow root - In real life: The kitchen behind the staff door
- In JavaScript: The shelf's shadow root
- In real life: Calling out
- In JavaScript:
bubbles: true - In real life: Calling through the open door
- In JavaScript:
composed: trueas well - In real life: "The kitchen says…"
- In JavaScript: Outside,
event.targetistea-shelf
Try all four sets of options, and press the button each time:
<tea-shelf></tea-shelf> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { const options = {}; this.dispatchEvent(new CustomEvent("tea-add", options)); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { console.log("The page heard it, from", event.target.localName); });</script><script src="tea-shelf.js"></script>Nothing prints. The event stays on the cup, and nobody listens there. Without bubbles, it never goes up to the shadow root.
- Line 8 holds the options. Your choice changes it.
- Lines 15 to 17 are the page's listener, on
document. It prints the tag name ofevent.target. - In the
tea-shelf.jstab, line 5 puts a cup in the shelf's shadow root. - Line 6 listens inside the shadow root, and line 7 listens on the shelf itself.
The page only hears the event with both options. And it hears it from tea-shelf, not from tea-cup. Outside a shadow root, the browser points event.target at the host, the element the shadow root belongs to. That's called retargeting. It keeps the shelf's inside private.
bubbles alone, the cup's event climbs to the top of the shelf's shadow root and stops. With composed too, it crosses out and climbs to document. Outside, its target is tea-shelf.The composed: true choice on its own is the odd one. The event leaves the shadow root and reaches the host, but goes no higher, because it doesn't bubble. Lit's docs describe the same thing. Westbrook Johnson calls composed: false the private fields of events: a component can use events inside its shadow root, and nobody outside sees them.
So give a component's public events bubbles: true and composed: true. You can't know where your tag will end up. One day it may sit in someone else's shadow root. Web Awesome sets both on every event from lesson 2.2. Keep composed: false for events only your component's own inside should hear.
Stage 3 goes deeper, in its lessons on composed events and event retargeting. Lesson 2.2 showed retargeting once, from the page's side.
How do you make a custom event cancelable?
Asha's shop has one more rule. After checkout, an order is locked. Ravi's cup now has a Remove button, and it must not remove a tea from a locked order. But the cup doesn't know about checkout. Only the page does.
So the cup asks first. Before it does anything, it dispatches tea-remove with cancelable: true. A listener may call event.preventDefault(). Then dispatchEvent() gives back false, and the cup stays where it is.
A waiter sees a plate that looks finished. She doesn't take it at once. She asks, "Shall I clear this?" If the guest says "Not yet", she leaves it. If the guest says nothing, she clears it.
- In real life: "Shall I clear this?"
- In JavaScript: Dispatching the cancelable
tea-removefirst - In real life: "Not yet"
- In JavaScript:
event.preventDefault() - In real life: Listening to the answer
- In JavaScript: Checking what
dispatchEvent()gave back - In real life: Clearing the plate
- In JavaScript:
this.remove(), only when the answer allows it
<tea-cup></tea-cup><label><input type="checkbox"> Order locked</label> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Remove green tea</button>"; this.addEventListener("click", () => { const options = { bubbles: true, cancelable: true }; const event = new CustomEvent("tea-remove", options); if (this.dispatchEvent(event)) { this.remove(); } else { console.log("The page said no"); } }); } } customElements.define("tea-cup", TeaCup); const lock = document.querySelector("input"); document.addEventListener("tea-remove", (event) => { if (lock.checked) event.preventDefault(); });</script>Tick Order locked, then press Remove. The page calls preventDefault(), dispatchEvent() gives back false, and the cup prints The page said no and stays. Untick the box, and Remove works.
- Line 9 sets the options. With
cancelable: true, a listener may cancel the event. - Line 11 dispatches the event and checks the answer, in one line.
- Line 12 runs only when the answer is
true. The built-inremove()method takes the cup off the page. - Line 14 runs when it's
false, and printsThe page said no. - Lines 22 and 23 are Asha's listener. When the order is locked, it calls
preventDefault().
Now pick Not cancelable, tick the box, and press Remove. The page still calls preventDefault(), but the call does nothing, and the cup goes. preventDefault() only works on a cancelable event, as the Custom events lesson showed.
dispatchEvent(). When it calls preventDefault(), dispatchEvent() gives back false, and the cup stays. Otherwise it gives back true, and the cup removes itself.Notice who does the work. preventDefault() doesn't stop anything by itself. It only marks the event as canceled. The cup has to read that answer, and skip its own action.
Asking before, telling after
Web Awesome's dialog works the same way. Its WaHideEvent class calls super("wa-hide", { bubbles: true, cancelable: true, composed: true }). The dialog dispatches it when something asks it to close. Then it checks defaultPrevented, the event's own flag for "a listener canceled me". If it's true, the dialog stays open and pulses. Web Awesome's docs suggest it for cases like a dialog whose closing would lose the user's work.
Once it has closed, the dialog dispatches a second event, wa-after-hide. That one isn't cancelable: it's too late to say no. The browser's popovers have the same pair. A listener can cancel beforetoggle when a popover is about to open, and it stays closed. The toggle event that follows can't be canceled.
So for an action the page might want to stop, dispatch a cancelable event before it. Add a plain one after it if the page needs to know it's done. The DOM Standard says it this way: an event tells about something that happened, and can change what happens next, through preventDefault().
Should you use CustomEvent or extend Event?
CustomEvent isn't the only way to send data. Event is a class, and a class can be extended. Lit's docs call both ways reasonable. Fagnani goes further. He says CustomEvent only exists because JavaScript couldn't extend built-in classes when it was added. Here is tea-add as its own class:
class TeaAddEvent extends Event {
static type = "tea-add";
constructor(tea, count) {
super(TeaAddEvent.type, { bubbles: true, composed: true });
this.tea = tea;
this.count = count;
}
}
const cup = document.createElement("tea-cup");
cup.addEventListener(TeaAddEvent.type, (event) => {
console.log(event.tea, event.count, event instanceof TeaAddEvent);
});
cup.dispatchEvent(new TeaAddEvent("Green tea", 2));- Line 1 makes a class,
TeaAddEvent, that extendsEvent. - Line 2 keeps the event's name in a static field: a value on the class itself, read as
TeaAddEvent.type. - Line 5 calls
super()with the name and the options. EveryTeaAddEventbubbles and is composed, so nobody can forget. - Lines 6 and 7 keep the data in the event's own fields.
- Line 12 listens with the same static name, so a typo can't creep in.
- Line 13 prints
Green tea 2 true. The listener readsevent.tea, notevent.detail.tea. Andinstanceofsays which class made the event.
Leaf and Kettle used to take orders on blank notes. Each waiter wrote them a different way, and the kitchen had to guess. Now there's a printed form. It has a title at the top, and boxes for the tea and the number of cups. Every copy looks the same.
- In real life: A blank note
- In JavaScript:
CustomEventand itsdetail, which can hold anything - In real life: The printed form
- In JavaScript: A class that extends
Event - In real life: The title at the top
- In JavaScript:
static type = "tea-add" - In real life: The labelled boxes
- In JavaScript: Fields like
event.teaandevent.count - In real life: Every copy the same
- In JavaScript: The constructor sets the options every time
Here is the same event both ways. Read each row across:
| Question | CustomEvent | A class that extends Event |
|---|---|---|
| Where is the data? | In event.detail. | In the event's own fields, like event.tea. |
| Where are the name and options written? | At every new CustomEvent() call. | Once, in the constructor. |
| How can a listener tell which event it got? | By its name only. | By its name, or with instanceof. |
| What does TypeScript know? | What you write in CustomEvent<…> each time. | The class is the type, with its fields. |
| When is it a good fit? | A quick event, or a team that wants all data in detail. | Several fields, many components, or typed code. |
Web Awesome mixes the two. Its WaHideEvent extends Event, as lesson 2.2 showed, but keeps its data in a field called detail. So listeners written to read detail still work with it. MDN's events guide shows both ways too.
Field names to avoid
An event already has properties of its own: type, target, timeStamp, and more. Don't reuse their names for your fields. This one throws on purpose:
class TeaAddEvent extends Event {
constructor(tea) {
super("tea-add");
this.target = tea;
}
}
new TeaAddEvent("Green tea");Line 4 tries to set target. Event gives target a getter and no setter. So Chrome throws TypeError: Cannot set property target of #<Event> which has only a getter. Call the field tea, and it works. In a class that extends CustomEvent, detail is taken too.
Types for every listener
In TypeScript, the class is also the event's type. Add it to GlobalEventHandlersEventMap, the list TypeScript keeps of event names and their types. Then every listener knows what it gets:
class TeaAddEvent extends Event { static type = "tea-add"; tea: string; constructor(tea: string) { super(TeaAddEvent.type, { bubbles: true, composed: true }); this.tea = tea; }} declare global { interface GlobalEventHandlersEventMap { "tea-add": TeaAddEvent; }} document.addEventListener("tea-add", (event) => { console.log(event.tea); // ^?}); export {};Lines 11 to 15 add tea-add to the list. So on line 17, event is a TeaAddEvent, and on line 18, event.tea is a string. Line 22, export {}, makes the file a module, which declare global needs. Web Awesome's hide.ts does the same for wa-hide.
When is CustomEvent the better pick? Burton Smith, who builds a component library, names a few cases. A team may want all custom data in one place, detail. Or many components may share a helper like emit(name, detail). For one quick event, CustomEvent is fine. For events with several fields, used across a kit, a class is clearer.
How should you name custom events?
A listener has to type the name exactly. Event names care about capital letters, so a listener for tea-add never hears Tea-Add. Pick names that are easy to get right, and hard to mix up with anyone else's.
In a busy food court, every stall has orders ready all day. If each one just called "Order ready!", nobody would know where to go. So each stall calls its own name first: "Leaf and Kettle, order ready!"
- In real life: Many stalls calling at once
- In JavaScript: Many components' events on one page
- In real life: "Leaf and Kettle, …"
- In JavaScript: The
tea-prefix - In real life: "…order ready!"
- In JavaScript: A plain word for what happened, like
add
- Lowercase, with hyphens.
tea-addis lowercase, like the platform'sclickandbeforetoggle. Hyphens keep longer names readable, like Web Awesome'swa-after-hide. - A prefix for your kit.
tea-keepstea-addapart from other libraries' events, aswa-does for Web Awesome. - No
onin front.onbelongs to handler names likeonclick. The event itself isclick. - A plain word for what happened. The platform uses short words:
inputwhile the user types,changeonce they're done. When the page may say no, use a pair: a cancelable event before, and one after. - No built-in names with a new meaning. An event called
changereaches everychangelistener. Web Awesome's rating does dispatchchange, but it means what it means on an input: the user picked a new value, and the listener readsevent.target.value.
One name can serve many components in a kit. Web Awesome's dialog and details both dispatch wa-show. Cory LaViska, who created Shoelace, explains why Shoelace never used names like sl-dialog-show: a button fires click, not button-click. When components nest, a listener checks event.target to see which one spoke.
A built-in name catches the wrong listeners
Here a cup borrows the name change, inside a form that saves a note:
<form> <input placeholder="A note for the kitchen"> <tea-cup></tea-cup></form> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = '<button type="button">Add green tea</button>'; this.addEventListener("click", () => { const detail = { count: 1 }; this.dispatchEvent(new CustomEvent("change", { bubbles: true, detail })); }); } } customElements.define("tea-cup", TeaCup); document.querySelector("form").addEventListener("change", (event) => { console.log("Saving the note:", event.target.value); });</script>- Lines 1 to 4 put a note box and a cup in a form.
- Line 12 dispatches the cup's event as
change, with a count indetail. - Lines 18 to 20 are the form's listener. It saves the note whenever something inside the form fires
change.
Type Less sugar in the box and press Tab. The console prints Saving the note: Less sugar. Now press Add. It prints Saving the note: undefined. The form caught the cup's event, and a cup has no value. Call it tea-change, and the form never sees it.
No on attribute for a custom event
<button onclick="…"> works because HTML knows onclick. The HTML Standard keeps a fixed list of these handler attributes, for its own events. A custom event isn't on the list:
<tea-cup ontea-add="console.log('The attribute ran')"></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { this.dispatchEvent(new CustomEvent("tea-add", { bubbles: true })); }); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.addEventListener("tea-add", () => console.log("addEventListener ran")); console.log("onclick" in cup, "ontea-add" in cup);</script>- Line 1 writes
ontea-addon the cup, with code in it. - Line 15 listens with
addEventListener(). - Line 16 prints
true false. The cup has anonclickproperty, but noontea-add.
Press Add. The console prints addEventListener ran, and nothing else. To the browser, the attribute is only text. So tell the people who use your component to listen with addEventListener().
When should a web component dispatch an event?
Lesson 5.1 gave the cup its input: attributes and properties the page sets. Events are its output. They go the other way, and they carry a different kind of news:
- Properties say what the page wants. The page sets
cup.count = 3. - Events say what happened without the page. The user pressed Add, or the timer ran out.
So dispatch an event when something changes that only your component knows about. The user did something inside it. Or, in web.dev's examples, a timer or an animation finished, or something finished loading. Lit's docs add the other half. Don't dispatch for changes the page made through a property or an attribute. Built-in elements work that way:
const input = document.createElement("input");
input.addEventListener("input", () => console.log("An input event"));
input.addEventListener("change", () => console.log("A change event"));
input.value = "Green tea";
console.log("The value is", input.value);- Lines 2 and 3 listen for
inputandchange, the two events typing fires. - Line 4 sets the value from a script.
- Line 5 prints
The value is Green tea. Neither listener ran.
The page knows it just set the value. An event would only repeat it back. web.dev warns it can even start an endless loop with data binding: a listener that copies the value back sets it again, and that fires the event again. Sort these changes:
- The user presses the cup's Add button
- The brewing timer reaches zero
- An image inside the cup finishes loading
- The user types a new amount in the cup's box
- The page sets
cup.count = 3 - The page calls
cup.setAttribute("tea", "Mint tea") - A script sets an input's
value
Sort each change by whether the cup should dispatch an event for it.
Update first, then dispatch
MDN spells out one more thing. The browser queues its own events for later, but dispatchEvent() runs every listener before it returns. So anything a listener reads must already be up to date. It's like writing an order on the board before you call it out: anyone who looks up sees the right order.
<tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { count = 0; connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { this.dispatchEvent(new Event("tea-add", { bubbles: true })); this.count += 1; }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { console.log("Cups in the cart:", event.target.count); });</script>Press Add twice. The page prints 0, then 1: always one behind. The listener runs inside dispatchEvent() on line 9, before line 10 counts the cup.
Line 5 gives every cup a count field, starting at 0. Line 9 dispatches tea-add, a plain Event with no detail. Line 17 reads the count from event.target. With the first choice, line 10 counts only after the listener has printed. Swap the lines, and the page sees the right number.
Why it matters: a listener may read your properties, call your methods, or dispatch an event of its own. Finish your own update first, and every one of them sees the new state.
Adding an event to the tea kit
Back to Ravi's kit. Its brewing timer counts down and shows Ready. Asha wants to play a sound when a tea is ready. But her page can't see the timer finish. That's the web.dev case, activity inside a component, so the timer dispatches an event:
<p>Green tea: <tea-timer seconds="2"></tea-timer></p><p>Mint tea: <tea-timer seconds="3"></tea-timer></p> <script type="module"> import { TeaTimerDoneEvent } from "./tea-kit/tea-timer.js"; document.addEventListener(TeaTimerDoneEvent.type, (event) => { console.log(`Done after ${event.seconds} s, showing ${event.target.textContent}`); });</script>- Lines 1 and 2 are two timers, for 2 and 3 seconds.
- Line 5 imports the timer's event class from the kit.
- Line 7 listens on
documentforTeaTimerDoneEvent.type, which istea-timer-done. - Line 8 prints the seconds from the event, and what the timer shows.
After 2 seconds, the console prints Done after 2 s, showing Ready. A second later, it prints Done after 3 s, showing Ready. One listener hears both timers, because the event bubbles.
Open the tea-kit/tea-timer.js tab:
- Lines 3 to 10 are
TeaTimerDoneEvent. Line 4 holds its name, and line 7 setsbubblesandcomposedevery time. - Line 27 keeps the starting seconds, for the event.
- Line 32 shows Ready first. Then lines 34 and 35 stop the timer and dispatch, so a listener sees a finished timer.
- Lines 19 to 21, the
secondssetter, dispatch nothing. The page made that change.
Because the event is composed, it also reaches the page when a timer sits in another component's shadow root, as the shelf's cup did. Why it matters: Asha has one place to hook in. She listens for tea-timer-done, anywhere on the page.
Common mix-ups
- "Events I make bubble, like clicks do." No.
bubblesstarts asfalse. Set it, or a listener on a parent never runs. - "composed: true makes an event bubble." No. They're separate.
composedalone reaches the host and stops. - "The page can't hear my component without composed." No. An event dispatched on your own element starts in the page's tree.
composedmatters when your element sits in another shadow root. - "preventDefault() stops the component by itself." No. It only marks the event. The component checks what
dispatchEvent()gave back, and skips its action. - "dispatchEvent() sends the event later." No. Every listener runs before it returns. Update your state first.
- "A custom event gets an on attribute, like onclick." No. HTML only knows the
onattributes for its own events. UseaddEventListener(). - "A component should fire change when the page sets its value." No. Built-in inputs stay quiet then. Dispatch for what the user or the component did.
- "CustomEvent is the only way to send data." No. A class that extends
Eventcan carry its own fields.
Practice exercises
Answer first, then use the hints. The results run live, so you can check yourself.
What does line 2 print?
const event = new CustomEvent("tea-add", { detail: 3 });
console.log(event.detail, event.bubbles);3 false. detail holds the 3 from line 1. bubbles wasn't set, so it has its default, false.
What does line 4 print?
const cup = document.createElement("tea-cup");
cup.addEventListener("tea-remove", (event) => event.preventDefault());
const allowed = cup.dispatchEvent(new CustomEvent("tea-remove"));
console.log(allowed);true. The listener calls preventDefault(), but the event isn't cancelable, so nothing is canceled. dispatchEvent() gives back false only for a canceled event.
Press Add: nothing prints. Fix line 9. What does the console print after one click?
<tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { const detail = { tea: "Green tea" }; dispatchEvent(new CustomEvent("tea-add", { bubbles: true, detail })); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { console.log("Added", event.detail.tea); });</script><tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { const detail = { tea: "Green tea" }; this.dispatchEvent(new CustomEvent("tea-add", { bubbles: true, detail })); }); } } customElements.define("tea-cup", TeaCup); document.addEventListener("tea-add", (event) => { console.log("Added", event.detail.tea); });</script>Added Green tea. On its own, dispatchEvent() means window.dispatchEvent(), so the event started at the window, above document, and never passed it. With this., it starts on the cup and bubbles up to document.
The cup lives in the shelf's shadow root, and the page hears nothing. Make the page hear it. What does the console print after one click?
<tea-shelf></tea-shelf> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { this.dispatchEvent(new CustomEvent("tea-add", { bubbles: true })); }); } } customElements.define("tea-cup", TeaCup); class TeaShelf extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<tea-cup></tea-cup>"; } } customElements.define("tea-shelf", TeaShelf); document.addEventListener("tea-add", (event) => { console.log("Heard from", event.target.localName); });</script><tea-shelf></tea-shelf> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Add green tea</button>"; this.addEventListener("click", () => { this.dispatchEvent(new CustomEvent("tea-add", { bubbles: true, composed: true })); }); } } customElements.define("tea-cup", TeaCup); class TeaShelf extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = "<tea-cup></tea-cup>"; } } customElements.define("tea-shelf", TeaShelf); document.addEventListener("tea-add", (event) => { console.log("Heard from", event.target.localName); });</script>Heard from tea-shelf. With composed: true, the event crosses out of the shelf's shadow root and bubbles to document. Outside, the browser retargets it to the host, tea-shelf.
The order is locked, and Remove prints Kept undefined. The page reads event.tea. Make tea-remove a class that extends Event, with a tea field. What does Remove print then?
<tea-cup tea="Green tea"></tea-cup><label><input type="checkbox" checked> Order locked</label> <script> class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Remove</button>"; this.addEventListener("click", () => { const tea = this.getAttribute("tea"); const event = new CustomEvent("tea-remove", { bubbles: true, cancelable: true, detail: { tea } }); if (this.dispatchEvent(event)) this.remove(); }); } } customElements.define("tea-cup", TeaCup); const lock = document.querySelector("input"); document.addEventListener("tea-remove", (event) => { if (!lock.checked) return; event.preventDefault(); console.log("Kept", event.tea); });</script><tea-cup tea="Green tea"></tea-cup><label><input type="checkbox" checked> Order locked</label> <script> class TeaRemoveEvent extends Event { static type = "tea-remove"; constructor(tea) { super(TeaRemoveEvent.type, { bubbles: true, composed: true, cancelable: true }); this.tea = tea; } } class TeaCup extends HTMLElement { connectedCallback() { this.innerHTML = "<button>Remove</button>"; this.addEventListener("click", () => { const tea = this.getAttribute("tea"); const event = new TeaRemoveEvent(tea); if (this.dispatchEvent(event)) this.remove(); }); } } customElements.define("tea-cup", TeaCup); const lock = document.querySelector("input"); document.addEventListener("tea-remove", (event) => { if (!lock.checked) return; event.preventDefault(); console.log("Kept", event.tea); });</script>Kept Green tea. The page reads event.tea, and a CustomEvent keeps its data in detail, so it printed Kept undefined. The class puts tea on the event itself, and its constructor makes every tea-remove cancelable.
On Web Awesome's Dialog page, listen on document for wa-hide, and print its cancelable, bubbles, and composed. Close a dialog. What does it print?
document.addEventListener("wa-hide", (event) => {
console.log(event.cancelable, event.bubbles, event.composed);
});true true true. WaHideEvent passes bubbles: true, cancelable: true, and composed: true to super(). It bubbles and is composed so a page hears it from anywhere. It's cancelable so a page can keep the dialog open.
Check your understanding
For each question, ask how far the event goes, who can stop it, and when its listeners run.
Question 1 of 7A cup inside a shelf's shadow root dispatches
tea-addwith{ bubbles: true }. Does a listener ondocumenthear it?Choose an answer to see the explanation.
Question 2 of 7What does this tea-add listener print?
Read the code, then predictconst cup = document.createElement("tea-cup"); cup.count = 0; cup.addEventListener("tea-add", () => console.log(cup.count)); cup.dispatchEvent(new Event("tea-add")); cup.count += 1;Choose an answer to see the explanation.
Question 3 of 7A listener called
preventDefault()on the cup's cancelabletea-remove. What must the cup do?Choose an answer to see the explanation.
Question 4 of 7Which name suits an event the tea kit's cup dispatches when a tea is added?
Choose an answer to see the explanation.
Question 5 of 7What does
<tea-cup ontea-add="save()">do when the cup dispatchestea-add?Choose an answer to see the explanation.
Question 6 of 7The page sets
cup.count = 3. Should the cup dispatch atea-changeevent?Choose an answer to see the explanation.
Question 7 of 7Why does
this.target = teathrow inside the constructor of anEventsubclass?Choose an answer to see the explanation.
Key takeaways
- A component talks back with
this.dispatchEvent(event). The page listens withaddEventListener(). new CustomEvent(type, { detail })carries data indetail. Its other options all start asfalse.- Set
bubbles: trueso a parent or the page can listen once, higher up. - Set
composed: truetoo, so the event can leave any shadow root your component ends up in. Outside, it seems to come from the host. - For an action the page may stop, dispatch a cancelable event first, and skip the action when
dispatchEvent()gives backfalse. - A class that extends
Eventkeeps the name and options in one place, carries real fields, and is its own type. - Name events in lowercase, with your prefix, without
on, and never with a built-in name for a new meaning. - Dispatch for what the user or the component did, never for what the page set. Update your state first.
Remember the one-liner.
Properties come in, events go out: update your state, then dispatch a prefixed event that bubbles and is composed, and make it cancelable when the page may say no.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- DOM Standard: Interface Event, WHATWG.
- DOM Standard: Interface CustomEvent, WHATWG.
- DOM Standard: dispatchEvent(), WHATWG.
- DOM Standard: Action versus occurrence, WHATWG.
- HTML Standard: Event handlers on elements, WHATWG.
- Event() constructor, MDN.
- CustomEvent() constructor, MDN.
- EventTarget: dispatchEvent() method, MDN.
- Event: composed property, MDN.
- DOM events: Creating and dispatching events, MDN.
- Lit: Events, Lit.
- Dialog: Preventing the dialog from closing, Web Awesome.
- hide.ts at v3.15.0, the WaHideEvent class, Web Awesome.
- dialog.ts at v3.15.0, requestClose(), Web Awesome.
- Custom element best practices: Events, web.dev.
- Stop Using CustomEvent, Justin Fagnani.
- Creating Truly Custom Events for Web Components, Burton Smith.
- composed: true considered harmful?, Westbrook Johnson.
- Custom Event Names and the Bubbling Problem, Cory LaViska.
Coming next: Designing a component API. Data goes down as properties, news comes up as events. Design an API that's easy to use and to change.