completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Dispatching events

Dispatch web component custom events the way built-in elements do: CustomEvent or an Event subclass, bubbles, composed, cancelable, and clear names.

By the end, you can
  • 01
    Dispatch an event from a componentMake it with new CustomEvent() or an Event subclass, and choose bubbles and composed on purpose.
  • 02
    Let the page say noMake the event cancelable, check what dispatchEvent() gives back, and skip the action when a listener called preventDefault().
  • 03
    Name 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.

A cup that tells the page about each addPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 puts a cup on the page, with a tea attribute.
  • 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. Its detail holds the tea, and bubbles: true lets 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.

One click, told to the page. On the left, the tea-cup component. An arrow leads to the event it makes, tea-add, with detail: { tea } and bubbles: true written under it. Another arrow leads to document, where the page's listener adds 1, so the cart shows Cart: 1 teas.the component<tea-cup>dispatches, line 14the eventtea-adddetail: { tea }bubbles: truethe pagedocumentthe listener adds 1Cart: 1 teas
The cup makes one event, 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.
Real-life analogyA kettle that whistles when it boils

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

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:

A CustomEvent with no optionsPop out in the code editor (opens in a new tab)JavaScript
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, and detail is null.
  • 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.

The options of new CustomEvent()
OptionDefaultWhat it does when you set it
detailnullCarries any data you give it, like { tea: "Green tea" }. Listeners read event.detail.
bubblesfalseThe event climbs from your element up to the page, so a listener higher up hears it.
composedfalseThe event may leave the shadow root it started in.
cancelablefalseA 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:

dispatchEvent() runs the listener, then gives back truePop out in the code editor (opens in a new tab)JavaScript
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:

The same event without and with bubblesPop out in the code editor (opens in a new tab)JavaScript
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 prints The shop heard the second add.
The same event twice. On the left, without bubbles: a main element above a tea-cup, and nothing reaches main. On the right, with bubbles: true: the same two elements, and an arrow climbs from tea-cup up to main, which prints The shop heard the second add.without bubbles<main>nothing reaches main<tea-cup>the first addwith bubbles: true<main><tea-cup>The shop heard the second add
The first 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, and change all bubble. Lit's docs say to set bubbles so 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.

Real-life analogyCalling out in a staff-only kitchen

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: true as well
In real life: "The kitchen says…"
In JavaScript: Outside, event.target is tea-shelf

Try all four sets of options, and press the button each time:

Playground: where does tea-add reach?
A cup inside a shelf's shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Nobody hears it

Nothing prints. The event stays on the cup, and nobody listens there. Without bubbles, it never goes up to the shadow root.

Line 8 changes with your choice. Press the button in the result, then read the console. The tea-shelf.js tab holds the shelf: it listens inside its shadow root, and on itself.
  • 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 of event.target.
  • In the tea-shelf.js tab, 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.

Two events from a tea-cup inside the shadow root of a tea-shelf. Cards from top to bottom: document, tea-shelf, and a window called shadow root that holds tea-cup. On the left, an arrow marked bubbles: true rises from tea-cup and stops at the top of the shadow root. On the right, an arrow marked bubbles and composed rises from tea-cup out of the shadow root up to document, where the target is tea-shelf.document<tea-shelf>shadow root<tea-cup>{ bubbles: true }stops at the roottarget: tea-shelfbubbles: true,composed: true
With 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.

Real-life analogyA waiter who asks before clearing the plates

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-remove first
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
Playground: can the page say no?
A cup that asks before it goesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The page can keep the cup

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 changes with your choice. The checkbox and the button are in the result. Press Run again to bring the cup back.
  • 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-in remove() method takes the cup off the page.
  • Line 14 runs when it's false, and prints The 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.

Two runs of the cancelable tea-remove event. Order locked: the page calls preventDefault(), dispatchEvent() gives back false, and the cup stays. Not locked: nobody calls preventDefault(), shown crossed out, dispatchEvent() gives back true, and the cup is removed.Order lockedtea-removepreventDefault()falsegiven backcup staysNot lockedtea-removepreventDefault()truegiven backcup removed
The page answers inside 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:

tea-add as a class that extends EventPop out in the code editor (opens in a new tab)JavaScript
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 extends Event.
  • 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. Every TeaAddEvent bubbles 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 reads event.tea, not event.detail.tea. And instanceof says which class made the event.
Real-life analogyA printed order form instead of a blank note

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: CustomEvent and its detail, 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.tea and event.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:

CustomEvent or a class that extends Event?
QuestionCustomEventA 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:

Setting this.target in the constructor throwsPop out in the code editor (opens in a new tab)JavaScript
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:

TeaAddEvent in TypeScript's list of eventsPop out in the code editor (opens in a new tab)TypeScript
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.

Real-life analogyFood court stalls that call out their own name

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-add is lowercase, like the platform's click and beforetoggle. Hyphens keep longer names readable, like Web Awesome's wa-after-hide.
  • A prefix for your kit. tea- keeps tea-add apart from other libraries' events, as wa- does for Web Awesome.
  • No on in front. on belongs to handler names like onclick. The event itself is click.
  • A plain word for what happened. The platform uses short words: input while the user types, change once 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 change reaches every change listener. Web Awesome's rating does dispatch change, but it means what it means on an input: the user picked a new value, and the listener reads event.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:

A cup that dispatches changePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 in detail.
  • 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:

An ontea-add attribute does nothingPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 writes ontea-add on the cup, with code in it.
  • Line 15 listens with addEventListener().
  • Line 16 prints true false. The cup has an onclick property, but no ontea-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:

An input stays quiet when a script sets its valuePop out in the code editor (opens in a new tab)JavaScript
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 input and change, 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:

Dispatch an event, or stay quiet?
  • 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
Try it yourself
0 of 7 correct

Sort each change by whether the cup should dispatch an event for it.

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

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.

Playground: count first, or tell first?
A cup that counts and tellsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The page reads the old count

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.

Lines 9 and 10 swap with your choice. The event carries no data: the listener reads the cup's count from event.target.

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:

One listener for every timer in the kitPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 document for TeaTimerDoneEvent.type, which is tea-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 sets bubbles and composed every 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 seconds setter, 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. bubbles starts as false. Set it, or a listener on a parent never runs.
  • "composed: true makes an event bubble." No. They're separate. composed alone 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. composed matters 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 on attributes for its own events. Use addEventListener().
  • "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 Event can carry its own fields.

Practice exercises

Answer first, then use the hints. The results run live, so you can check yourself.

Exercise 1 · Warm-upA detail and nothing else

What does line 2 print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const event = new CustomEvent("tea-add", { detail: 3 });
console.log(event.detail, event.bubbles);

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

    Exercise 2 · Warm-upSaying no to an event that can't be stopped

    What does line 4 print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const cup = document.createElement("tea-cup");
    cup.addEventListener("tea-remove", (event) => event.preventDefault());
    const allowed = cup.dispatchEvent(new CustomEvent("tea-remove"));
    console.log(allowed);

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

      Exercise 3 · PracticeThe cart that never hears

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

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

        Exercise 4 · PracticeA cup on a shelf

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

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

          Exercise 5 · ChallengeA TeaRemoveEvent class

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

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

            Exercise 6 · ChallengeWeb Awesome's wa-hide

            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?

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

              Check your understanding

              For each question, ask how far the event goes, who can stop it, and when its listeners run.

              The dispatching events quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A cup inside a shelf's shadow root dispatches tea-add with { bubbles: true }. Does a listener on document hear it?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this tea-add listener print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const 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.

              3. Question 3 of 7A listener called preventDefault() on the cup's cancelable tea-remove. What must the cup do?

                Choose an answer to see the explanation.

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

              5. Question 5 of 7What does <tea-cup ontea-add="save()"> do when the cup dispatches tea-add?

                Choose an answer to see the explanation.

              6. Question 6 of 7The page sets cup.count = 3. Should the cup dispatch a tea-change event?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why does this.target = tea throw inside the constructor of an Event subclass?

                Choose an answer to see the explanation.

              Key takeaways

              • A component talks back with this.dispatchEvent(event). The page listens with addEventListener().
              • new CustomEvent(type, { detail }) carries data in detail. Its other options all start as false.
              • Set bubbles: true so a parent or the page can listen once, higher up.
              • Set composed: true too, 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 back false.
              • A class that extends Event keeps 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:

              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.

              CompleteFrontend Clear concepts. Working examples.